首页 > 解决方案 > 如何将 twitterscraper 输出保存为 json 文件

问题描述

我阅读了文档,但文档仅提到将输出保存为.txt文件。我尝试修改代码以将输出保存为 JSON。

另存为.txt

from twitterscraper import query_tweets

if __name__ == '__main__':
    list_of_tweets = query_tweets("Trump OR Clinton", 10)

    #print the retrieved tweets to the screen:
    for tweet in query_tweets("Trump OR Clinton", 10):
        print(tweet)

    #Or save the retrieved tweets to file:
    file = open(“output.txt”,”w”)
    for tweet in query_tweets("Trump OR Clinton", 10):
        file.write(tweet.encode('utf-8'))
    file.close()

我尝试将其修改为另存为 JSON:

 output = query_tweets("Trump OR Clinton", 10)
 jsonfile = open("tweets.json","w")
    for tweet in output:
        json.dump(tweet,jsonfile)
    jsonfile.close()

TypeError: Object of type Tweet is not JSON serializable

但我收到上述类型错误

如何将输出保存为 JSON?我知道在终端中输入命令会创建 JSON,但我想编写一个 python 版本。

标签: jsonpython-3.x

解决方案


我们需要先将每条推文转换为 dict,因为 Python 类对象不能序列化为 JSON。查看第一个对象,我们可以看到可用的方法和属性,如下所示help(list_of_tweets[0]):访问__dict__我们看到的第一个对象:

# print(list_of_tweets[0].__dict__)
{'user': 'foobar',
'fullname': 'foobar',
'id': '143846459132929',
'url': '/foobar/status/1438420459132929',
'timestamp': datetime.datetime(2011, 12, 5, 23, 59, 53),
'text': 'blah blah',
'replies': 0,
'retweets': 0,
'likes': 0,
'html': '<p class="TweetTextSize...'}

在将其转储为 json 之前,我们需要将datetime对象转换为字符串。

tweets = [t.__dict__ for t in list_of_tweets]
for t in tweets:
    t['timestamp'] = t['timestamp'].isoformat()

然后我们可以使用 json 模块将数据转储到文件中。

import json

with open('data.json', 'w') as f:
    json.dump(tweets, f)

推荐阅读