如何使用python提取提及?

时间:2016-11-26 07:02:17

标签: python twitter

我正在使用python处理代码,从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']

提及的是' @'符号,包含所有字母数字字符,但不包括空格字符,标点符号或推文结尾。

如何从字符串中提取提及?抱歉,我还没有了解正则表达式,还有其他方法吗?

2 个答案:

答案 0 :(得分:3)

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

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

示例代码

import re

text = "@RayFranco is answering to @jjconti, this is a real '@username83' but this is an@email.com, and this is a @probablyfaketwitterusername";

result = re.findall("(^|[^@\w])@(\w{1,15})", text)

print(result);

返回:

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

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

  

您的用户名不能超过15个字符。你的真名可以   更长(20个字符),但用户名保持较短   轻松。用户名只能包含字母数字字符(字母   A-Z,数字0-9),但下划线除外,如上所述。   检查以确保您所需的用户名不包含任何符号,   破折号或空格。

答案 1 :(得分: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']

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

re.sub("[\w]+@[\w]+\.[c][o][m]", "", input_string)