【问题标题】:Transforming Tweepy data from text file into dataframe将 Tweepy 数据从文本文件转换为数据框
【发布时间】:2018-04-21 23:41:41
【问题描述】:

我正在尝试从提取到文本文件中的 tweepy 数据创建一个数据框。

但是,当我尝试使用我想要的列创建数据框时,没有生成任何内容。代码运行,但没有输出。

下面是代码:

#写入文本文件 使用 open("jsontweet3.txt", "a") 作为 txtfile: txtfile.write('tweet_id retweet_count favorite_count \n')

#pulling tweet info
for tweet_id in fdf.tweet_id:
    try:
        twitinfo = tweetapi.get_status(str(tweet_id), tweet_mode='extended')

    except:
        # Not able to get tweet --> add to failed_tweets list
        failed_tweets.append(tweet_id)

    else:
        # only gets executed if the try clause did not fail         
        retweets = twitinfo.retweet_count
        favorites = twitinfo.favorite_count
        txtfile.write(str(twitinfo)+' '+str(retweets)+' '+str(favorites)+'\n')


tdf = pd.DataFrame(columns=['tweet_id','retweet_count','favorite_count'])
with open('jsontweet3.txt','r') as file:

for line in file:
    twitinfo,retweets,favorites= line[:-1].split(' ')
    tdf = tdf.append({'tweet_id':twitinfo,'retweet_count':retweets,'favorite_count':favorites},ignore_index=True)

tdf

非常感谢所有帮助!

【问题讨论】:

  • for 循环需要缩进,因为它应该在 with 内。我认为for 行应该是for line in file.readlines():

标签: python python-3.x pandas dataframe


【解决方案1】:

除了我对for 循环和.readlines() 缩进的cmets,我建议:

1) 将 tweepy 数据写入 csv(用逗号分隔,而不是空格),然后 pd.read_csv() 将生成 csv

2) 在创建文本文件的同时创建数据框。只需在第一个 for 之前生成 tdf,然后在执行 txtfile.write() 时使用 tdf.append()

【讨论】:

    猜你喜欢
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2015-11-14
    • 2016-04-23
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多