因此,我使用tweet ID列表来查询Twitter API。我需要做的是遍历in,以便从Twitter获取相应的数据。然后,我需要将这些JSON文件存储到一个txt文件中,其中每个tweet的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)
上面的代码没有将每个文件放在自己的行上。
我希望我能为你提供足够的信息来帮助我。
提前感谢您的帮助。
发布于 2019-05-24 03:37:53
使用json.dump
将json
附加到文件中不包括换行符,因此它们都放在同一行中。我建议您将所有的json记录收集到一个list
中,然后使用join
并将其转储到一个文件中
tweets, drop_lst = [], []
for i in twt.tweet_id:
try:
tweet = api.get_status(i)
tweets.append(tweet._json)
except tp.TweepError:
drop_lst.append(i)
with open('data.txt', 'a') as fh:
fh.write('\n') # to ensure that the json is on its own line to start
fh.write('\n'.join(json.dumps(tweet) for tweet in tweets)) # this will concatenate the tweets into a newline delimited string
然后,要创建数据帧,您可以读取该文件并将所有内容缝合在一起
with open("data.txt") as fh:
tweets = [json.loads(line) for line in fh if line]
df = pd.DataFrame(tweets)
这里假设json
本身没有换行符,tweet中可能包含换行符,所以要小心
https://stackoverflow.com/questions/56281842
复制相似问题