【发布时间】:2020-05-19 09:25:54
【问题描述】:
大家好,我正在从事一个个人项目,在该项目中我正在搜索包含特定关键字的推文。我为每个关键字收集了大约 100 条最近的推文,并将它们保存到变量 x1_tweets、x2_tweets 和 x3_tweets。数据基本上是一个字典列表,字段如下所示:
['created_at', 'id', 'id_str', 'text', 'truncated', 'entities', 'metadata', 'source', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'in_reply_to_user_id', 'in_reply_to_user_id_str', 'in_reply_to_screen_name', 'user', 'geo', 'coordinates', 'place', 'contributors', 'is_quote_status', 'retweet_count', 'favorite_count', 'favorited', 'retweeted', 'lang']
然后我想将每个变量中的推文(只是文本)保存到 json 文件中。为此我定义了一个函数(该函数将字典列表保存到 json 文件中,obj 是字典列表,文件名是我要保存的名称):
def save_to_json(obj, filename):
with open(filename, 'w') as fp:
json.dump(obj, fp, indent=4, sort_keys=True)
为了只获取推文,我实现了以下代码:
for i, tweet in enumerate(x1_tweets):
save_to_json(tweet['text'],'bat')
但是到目前为止我还没有成功,谁能指导我正确的方向?提前致谢!
编辑:我正在使用 twitterAPI
【问题讨论】:
-
不完全确定您的问题是什么,但请检查
pickle进行序列化。你可以在这里看到一个例子:stackoverflow.com/questions/11218477/… -
嗨,我想使用 json 作为我的输出文件。我知道错误出现在最后一段代码中,但如果你想要我可以向你展示我的包含所有字段的 json 文件,我只是无法弄清楚它是什么?
-
当您提出问题时,如果遇到错误,您应该分享错误,或者显示输出是什么以及预期的输出应该是什么。否则无法回答。尽管如此,它可能与
json文档中的此警告有关:Note Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.
标签: python python-3.x twitter