【问题标题】:how to modify use my function to retrieve tweets如何修改使用我的功能来检索推文
【发布时间】: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


【解决方案1】:

您需要做的第一件事是将以下代码更改为:

def save_to_json(obj, filename):
    with open(filename, 'a') as fp:
        json.dump(obj, fp, indent=4, sort_keys=True) 

由于以下原因,您需要更改打开文件的模式。

w: 以只写模式打开。指针位于文件的开头,这将覆盖任何现有的同名文件。如果不存在同名文件,它将创建一个新文件。

a: 打开一个文件以添加新信息。指针位于文件末尾。如果不存在同名文件,则会创建一个新文件。

此外,sort_keys 没有任何意义,因为您只传递了 string 而不是 dict。同样,indent=4strings 没有意义。

如果您需要对推文文本进行索引,您可以使用以下代码:

tweets = {}    
for i, tweet in enumerate(x1_tweets):
    tweets[i] = tweet['text']
save_to_json(tweets,'bat.json')

上面的代码将创建一个dict,其中包含推文的索引,并在处理完所有推文后写入文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2023-03-30
    • 2014-09-10
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    相关资源
    最近更新 更多