[英]Organize by Twitter unique identifier using python
我有一个CSV文件,每行包含与特定tweet相关的信息(即,每行包含Lat,Long,User_ID,tweet等)。 我需要读取文件并通过User_ID整理推文。 我试图以给定的User_ID附加到具有该特定ID的所有推文上。
这是我想要的:
user_id: 'lat', 'long', 'tweet'
: 'lat', 'long', 'tweet'
user_id2: 'lat', 'long', 'tweet'
: 'lat', 'long', 'tweet'
: 'lat', 'long', 'tweet'
等等...
这是我的代码片段,可读取CSV文件并创建列表:
UID = []
myID = []
ID = []
f = None
with open(csv_in,'rU') as f:
myreader = csv.reader(f, delimiter=',')
for row in myreader:
# Assign columns in csv to variables.
latitude = row[0]
longitude = row[1]
user_id = row[2]
user_name = row[3]
date = row[4]
time = row[5]
tweet = row[6]
flag = row[7]
compound = row[8]
Vote = row[9]
# Read variables into separate lists.
UID.append(user_id + ', ' + latitude + ', ' + longitude + ', ' + user_name + ', ' + date + ', ' + time + ', ' + tweet + ', ' + flag + ', ' + compound)
myID = ', '.join(UID)
ID = myID.split(', ')
我建议您为此使用pandas
。 它不仅允许您像在问题中那样通过user_id
列出您的推文,而且还可以轻松地进行许多其他操作。
作为示例,请看一下NLTK的python笔记本 。 最后,您会看到一个非常接近您的操作,读取包含推文的csv
文件,
In [25]: import pandas as pd tweets = pd.read_csv('tweets.20150430-223406.tweet.csv', index_col=2, header=0, encoding="utf8")
In [25]: import pandas as pd tweets = pd.read_csv('tweets.20150430-223406.tweet.csv', index_col=2, header=0, encoding="utf8")
您还可以找到一个简单的操作:寻找特定用户的推文,
In [26]: tweets.loc[tweets['user.id'] == 557422508]['text'] Out[26]: id 593891099548094465 VIDEO: Sturgeon on post-election deals http://... 593891101766918144 SNP leader faces audience questions http://tc.. Name: text, dtype: object
要通过user_id
列出这些推文,您只需执行以下操作(这不在原始笔记本中),
In [9]:
tweets.set_index('user.id')[0:4]
Out[9]:
created_at favorite_count in_reply_to_status_id in_reply_to_user_id retweet_count retweeted text truncated
user.id
107794703 Thu Apr 30 21:34:06 +0000 2015 0 NaN NaN 0 False RT @KirkKus: Indirect cost of the UK being in ... False
557422508 Thu Apr 30 21:34:06 +0000 2015 0 NaN NaN 0 False VIDEO: Sturgeon on post-election deals http://... False
3006692193 Thu Apr 30 21:34:06 +0000 2015 0 NaN NaN 0 False RT @LabourEoin: The economy was growing 3 time... False
455154030 Thu Apr 30 21:34:06 +0000 2015 0 NaN NaN 0 False RT @GregLauder: the UKIP east lothian candidat... False
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.