【问题标题】:Organize by Twitter unique identifier using python使用 python 按 Twitter 唯一标识符组织
【发布时间】:2015-09-09 17:54:25
【问题描述】:

我有一个 CSV 文件,其中每一行都包含与特定推文有关的信息(即每一行包含纬度、经度、用户 ID、推文等)。我需要阅读文件并按 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(', ') 

【问题讨论】:

    标签: python twitter


    【解决方案1】:

    我建议您为此使用pandas。它不仅可以让你通过user_id 列出你的推文,就像你的问题一样,还可以很容易地进行许多其他操作。

    例如,看看this python notebook from NLTK。最后,您会看到一个非常接近您的操作,读取包含推文的csv 文件,

    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://t.c...
    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
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-15
      • 2020-01-07
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 2014-03-05
      • 2012-06-02
      • 2012-11-21
      相关资源
      最近更新 更多