根据推文文本在Python中分类推文类型(推文/转推/提及)
我参考了几个不同的例子,写了一个简单的Python脚本,可以解析Twitter Streaming API返回的JSON数据,并打印出每条推文的 screen_name
和 text
。我想修改我的代码,让它还能把每条推文分类为以下几种:
(1) 转发 --> 推文文本中有“RT @某用户名”
(2) 提及 --> 推文中有“@某用户名”,但没有“RT @某用户名”
(3) 推文 --> 推文中既没有“RT @某用户名”,也没有“@某用户名”
我可以在Excel中用以下公式做到这一点,但我还没想出怎么在Python中实现。
=IF(IFERROR(FIND("RT @",B2)>0,"False"),"Retweet",IF(IFERROR(FIND("@",B2)>0,"False"),"Mention","Tweet"))
现有代码
import json
import sys
from csv import writer
with open(sys.argv[1]) as in_file, \
open(sys.argv[2], 'w') as out_file:
print >> out_file, 'tweet_author, tweet_text, tweet_type'
csv = writer(out_file)
for line in in_file:
try:
tweet = json.loads(line)
except:
pass
tweet_text = tweet['text']
row = (
tweet['user']['screen_name'],
tweet_text
)
values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
csv.writerow(values)
1 个回答
3
我这里没有Python解释器,但应该类似于这个:
import re
def url_match(tweet):
match = re.match(r'RT\s@....+', tweet)
if match:
return "RT"
else:
match = re.match(r'@....+', tweet)
if match:
return "mention"
else
return "tweet"
注意:这个方法适用于这个分类,但如果你想获取用户名,也就是@USERNAME,你需要稍微调整一下。