【发布时间】: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 是的。并且该推文示例只是来自推特网站的示例,而不是我的代码。由于我的文件是从网络上抓取的,所以我不在这里发布它。不过谢谢你的建议