【发布时间】: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