0

我使用字典将推文存储到多个 json 文件中,其中每个字典都包含有关一条推文的信息。在每个字典中,我将用户 id (key="uid")、tweet id (key="id")、文本 (key="txt") 和时间戳 (key="ts") 存储为单独的键。

现在我想从 json 文件中读取字典,删除冗余推文(基于推文 ID),并将生成的非冗余推文存储到一个大的 json 文件中。

下面是其中一个 json 文件中的数据示例:

{"id": 1234, "txt":"text here 123", "ts":"Wed, 03 Apr 2013 12:03:28 +0000", "uid":12345}
{"id": 2345, "txt":"more text here", "ts":"Tue, 02 Apr 2013 16:50:20 +0000", "uid":23456}
{"id": 1234, "txt":"text here 123", "ts":"Wed, 03 Apr 2013 12:03:28 +0000", "uid":12345}

在示例中,第一条和第三条推文是多余的。因此,我想删除第三条推文。

我到目前为止的代码如下。由于我根据我对 Python 的(有限)经验以及网络上的其他示例创建了代码,因此它不起作用。我收到以下错误: JSONDecodeError: Extra data: line 1 column 192 - line 1 column 10166 (char 192 - 10166)

我认为我在正确的轨道上,至少在浏览目录中的文件和删除多余的推文方面。但是,我认为我的问题在于正确加载和读取 json 文件。任何帮助、帮助或指导将不胜感激。

(不,我不是为作业做这件事的学生——我是一名研究生,希望分析 Twitter 数据以进行我的研究。)

import string
import glob
import os
import simplejson as json

listoftweets = {} #to store all of the tweet ids

os.chdir("/mydir") #directory containing the json files with tweets

for f in glob.glob("*.json"):

    t = open(f,"r") #loading the json with tweets
    f1 = open(alltweets,"a") #open the json file to store all tweets

    for line in t:
        data = json.loads(line)
        tid = data['tweetid']

        if not listoftweets.has_key(tid): #if this isn't a redundant tweet
            json.dump(data,f1) #dump into the json file
            listoftweets[tid] = 0 #add this tweet id to the list

    t.close()
    f1.close()

编辑

我稍微修改了代码。似乎原始数据并未与每条推文一起存储在新行上——感谢 Gary Fixler。现在问题已解决,我遇到了另一个错误: Traceback
...
loading C:\Python27\lib\site-packages\simplejson__init__.py 451
decode C:\Python27\lib\site-packages\simplejson\decoder。 py 409
JSONDecodeError:额外数据:第 1 行第 233 列 - 第 2 行第 1 列(字符 233 - 456)

其他一些注意事项:谢谢 Wesley Baugh——我尽可能多地实施了建议的更改。

此外,有太多的推文无法一次加载所有内容——这些推文是在 3 个月内不断收集的。

更新的代码如下

listoftweets = {}
listoffiles = []

os.chdir("/mydir")

for f in glob.glob("*.json"):
    listoffiles.append(str(f))

t2 = open("cadillaccue_newline.json",'a')

for files in listoffiles:
    t = open(files,'r')
    for line in t:
        text = line
        text = text.replace('}{','}\n{')
        t2.write(text)
    t.close()

t2.close()


t = open("cadillaccue_newline.json",'r')
f1 = open("cadillaccue_alltweets.json",'a')

for line in t:
    data = json.loads(line)
    tid = data['id']

    if tid not in listoftweets:
        json.dump(data,f1)
        listoftweets[tid] = 0

t.close()
f1.close()
4

0 回答 0