2016-11-26 82 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),下劃線除外。 檢查以確保您所需的用戶名不包含任何符號, 破折號或空格。