【发布时间】:2019-05-23 19:31:06
【问题描述】:
所以我正在使用推文 ID 列表查询 Twitter API。我需要做的是遍历 ID,以便从 Twitter 获取相应的数据。然后我需要将这些 JSON 文件存储到一个 txt 文件中,其中每条推文的 JSON 数据都在自己的行中。稍后我将不得不逐行读取 txt 文件以从中创建 pandas df。
我试着给你一些假数据来告诉你结构。
twt.tweet_id.head()
0 000000000000000001
1 000000000000000002
2 000000000000000003
3 000000000000000004
4 000000000000000005
Name: tweet_id, dtype: int64
我不知道如何共享 JSON 文件,我什至不知道我是否可以。调用 tweet._json 后,我得到的是一个 JSON 文件。
drop_lst = [] # this is needed to collect the IDs which don't work
for i in twt.tweet_id: # twt.tweet_id is the pd.series with the IDs
try:
tweet = api.get_status(i)
with open('tweet_json.txt', 'a') as f:
f.write(str(tweet._json)+'\n') # tweet._json is the JSON file I need
except tp.TweepError:
drop_lst.append(i)
上述方法有效,但我认为我丢失了稍后创建数据帧所需的 JSON 结构
drop_lst = []
for i in twt.tweet_id:
try:
tweet = api.get_status(i)
with open('data.txt', 'a') as outfile:
json.dump(tweet._json, outfile)
except tp.TweepError:
drop_lst.append(i)
上面没有把每个文件放在自己的行上。
我希望我能够为您提供足够的信息来帮助我。
提前感谢您的所有帮助。
【问题讨论】: