如何使用python提取提到的内容?

2024-09-30 08:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python编写一个代码,从tweet文本中提取提到的内容。在

参数是tweet文本。这个函数应该返回一个包含tweet中所有提到内容的列表,按照它们在tweet中出现的顺序。返回列表中的每个提及都应该删除初始的提及符号,并且列表应该包含遇到的每个提及-包括重复,如果用户在推特。这里有两个例子:

>>>extract_mentions('@AndreaTantaros- You are a true journalistic\
professional. I so agree with what you say. Keep up the great\
work!@RepJohnLewis ')
['AndreaTantaros','RepJohnLewis']
>>>extract_mentions('@CPAC For all the closet #libertarians attending \
#CPAC2016 , I'll be there Thurs/Fri -- speaking Thurs. a.m. on the main\
stage. Look me up! @CPAC')
['CPAC','CPAC']

“提及”以“@”符号开头,包含所有字母数字字符(不包括空格字符、标点符号或tweet结尾)。在

如何从字符串中提取提到的内容?抱歉,我还没学过regex,还有其他方法吗?在


Tags: the代码文本内容列表符号extract字符
2条回答

使用regex

import re
input_string = '@AndreaTantaros- You are a true journalistic professional. I so agree with what you say. Keep up the great work!@RepJohnLewis '
result = re.findall("@([a-zA-Z0-9]{1,15})", input_string)

输出:['AndreaTantaros', 'RepJohnLewis']

如果要先删除电子邮件地址,只需执行以下操作:

^{pr2}$

您可以使用以下正则表达式,因为它忽略电子邮件地址。在

(^|[^@\w])@(\w{1,15})

示例代码

^{pr2}$

这将返回:

[('', 'RayFranco'), (' ', 'jjconti'), ("'", 'username83'), (' ', 'probablyfaketwi')]

注意,twitter允许最多15个字符作为twitter用户名。基于Twitter specs

Your username cannot be longer than 15 characters. Your real name can be longer (20 characters), but usernames are kept shorter for the sake of ease. A username can only contain alphanumeric characters (letters A-Z, numbers 0-9) with the exception of underscores, as noted above. Check to make sure your desired username doesn't contain any symbols, dashes, or spaces.

相关问题 更多 >

    热门问题