如何将twitterscraper输出另存为json文件

时间:2018-11-30 23:37:12

标签: json python-3.x

我阅读了文档,但是文档仅提到将输出另存为.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版本。

1 个答案:

答案 0 :(得分:0)

我们首先需要将每个tweet转换为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)