将文本文件中的Tweepy数据转换为数据帧

时间:2018-04-21 23:41:42

标签: python python-3.x pandas dataframe

我正在尝试从我拉入文本文件的tweepy数据创建数据框。

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

以下是代码:

#writing文本文件 打开(" 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

非常感谢所有帮助!

1 个答案:

答案 0 :(得分:0)

除了我对for循环和.readlines()缩进的评论之外,我建议:

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

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

时生成txtfile.write()
相关问题