json - 如何将 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 版本。
解决方案
我们需要先将每条推文转换为 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)
推荐阅读
- javascript - Vue Js,v-for循环,从深度Json数组中获取值
- javascript - 为什么我的文档 cookie 对象没有在 chrome 浏览器中存储任何 cookie?
- c# - Entity Framework Core 中两个实体之间的一对多和一对一关系
- java - 如何在我的跑步者中使用 toString 方法?
- javascript - 如何修复 npm 包中的功能问题?
- kubernetes - 版本“extensions/v1beta1”中没有类型“ReplicaSet”的匹配项
- deployment - Gatsby 动态路由在 gh-pages 部署时中断
- javascript - Svelte Sapper 在页面刷新时保留会话(重新加载)
- javascript - 带有参数的 javascript addEventListener 函数而不使用匿名函数
- clips - 如何通过 CLIPSIDE 中的不同选择获得 R7