2016-11-26 61 views
-2

我正在使用python从tweet文本中提取提及的代码。如何使用python来提取提及?

该参数是一条推文文本。这个函数应该按照它们在推文中出现的顺序返回一个包含推文中所有提及的列表。在返回的列表中的每个值得一提的有初始提取出符号和列表应包含遇到的每一个提 - 包括重复,如果用户不是tweet.Here中曾经提到更多的是两个例子:

>>>extract_mentions('@AndreaTantaros- You are a true journalistic\ 
professional. I so agree with what you say. Keep up the great\ 
[email protected] ') 
['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

使用regex

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

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

如果您想先删除电子邮件地址,只需做:

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

如果某人的电子邮件地址是 - [email protected]? –

+0

这取决于,你可以简单地将一个正则表达式匹配一个'.'后的三个字符,就像这样:'[\ w] + @ [\ w] + \。[a-z] {3}'。 OP没有提到她想要什么。 @WasiAhmad – Jarvis

+0

如果我的电子邮件地址是“hello @ example.ninja”,该怎么办?或'hello @ example.nl'?或'hello.there @ example.com'?或'hello + there @ example.com'? – Carpetsmoker

0

您可以使用下面的正则表达式,因为它无视电子邮件地址。

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

示例代码

import re 

text = "@RayFranco is answering to @jjconti, this is a real '@username83' but this is [email protected], and this is a @probablyfaketwitterusername"; 

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

print(result); 

这将返回:

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

需要注意的是,微博可以让最多15个字符的Twitter用户名。基于Twitter specs

您的用户名不能超过15个字符。您的真实姓名可以是 较长(20个字符),但为了便于使用,用户名会缩短。如上所述,用户名只能包含字母数字字符(字母 A-Z,数字0-9),下划线除外。 检查以确保您所需的用户名不包含任何符号, 破折号或空格。