【问题标题】:Cleaning out tweet json file using python使用 python 清理推文 json 文件
【发布时间】:2018-04-17 03:47:58
【问题描述】:

我有 twitter json 文件,想从这里提取特定信息。这个json文件的例子可以在这里找到,https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json

{
    "created_at": "Thu Apr 06 15:24:15 +0000 2017",
    "id_str": "850006245121695744",
    "text": "1\/ Today we\u2019re sharing our vision for the future of the Twitter API platform!\nhttps:\/\/t.co\/XweGngmxlP",
    "user": {
      "id": 2244994945,
      "name": "Twitter Dev",
      "screen_name": "TwitterDev",
      "location": "Internet",
      "url": "https:\/\/dev.twitter.com\/",
      "description": "Your official source for Twitter Platform news, updates & events. Need technical help? Visit https:\/\/twittercommunity.com\/ \u2328\ufe0f #TapIntoTwitter"
    },
    "place": {

    },
    "entities": {
      "hashtags": [

      ],
      "urls": [
        {
          "url": "https:\/\/t.co\/XweGngmxlP",
          "unwound": {
            "url": "https:\/\/cards.twitter.com\/cards\/18ce53wgo4h\/3xo1c",
            "title": "Building the Future of the Twitter API Platform"
          }
        }
      ],
      "user_mentions": [

      ]
    }
  }

我试图删除一些我不需要的项目,例如id_str。 所以我创建了一个包含我需要的键名称的列表,并迭代这个 json 文件(一个文件有超过一百万条推文)。我已经搜索了类似的问题并尝试实施回复的建议。

tags = ["created_at", "text", "retweet_count",
        "friends_count","followers_count","verified","place"]
for line in json_file:
    try:
        data = json.loads(line)
        for i in data.keys():
            if i not in tags:
                try:
                    del data[i]
                except:
                    continue
    except:
        continue

for line in json_file:
    data = json.loads(line)
    print(data)

但是,我的 json_file 是空的,它最终不会打印出任何内容。 而不是del data[i],我尝试了多种不同的方式,比如

del data[str(i)]
data.pop(i)

提前致谢!

【问题讨论】:

  • 编辑 Python 数据结构不会改变文件数据,您需要序列化回 JSON 并写入新文件。接下来,您从文件 两次 中读取,第二次您没有回溯到文件开头,文件位置仍在末尾,因此第二次循环不会读取更多数据.
  • @MartijnPieters 如果不改变文件数据,是不是还要打印出来?
  • 这就是我的评论的第二部分。添加json_file.seek(0) 以返回到文件的开头。
  • 您真的不应该捕获所有异常。仅捕获特定异常,我们甚至无法判断您的数据是否每次迭代都正确加载。
  • @MartijnPieters 是的。并且该推文示例只是来自推特网站的示例,而不是我的代码。由于我的文件是从网络上抓取的,所以我不在这里发布它。不过谢谢你的建议

标签: python json twitter


【解决方案1】:

你需要使用json.loads()一次读取json文件 所有标签都出现在data["tweets"]的下一级

import json

json_file = open("test.json").read()
tags = ["created_at", "text", "retweet_count", "friends_count","followers_count","verified","place"]

data = json.loads(json_file)

for i in data["tweet"].keys():
    if i not in tags:
        del data["tweet"][i] 

print data

【讨论】:

  • 他们有一个JSON lines file,所以不,他们不需要立即读取文件。这不是他们面临的问题。见Loading and parsing a JSON file with multiple JSON objects in Python
  • 考虑到他们给出的示例 json 似乎并非如此。此外,tweet 参数也很重要。此外,还可以将其转储到另一个文件中。
  • 他们给出的示例代码不会引发异常,并且它只有在数据为JSON行格式时才能工作。跨度>
  • 这是模棱两可的。我假设代码错误地将每一行读取为 json,其中只有整个文件是 json。
猜你喜欢
  • 2021-08-23
  • 2021-12-24
  • 2017-11-30
  • 1970-01-01
  • 2020-11-16
  • 2018-03-26
  • 2016-07-17
  • 1970-01-01
  • 2021-11-08
相关资源
最近更新 更多