python - 使用Python读取json文件中很长的行时出现内存错误

标签 python json

我有一个 1GB 的 json 文件,其中包含很长的行,当我尝试从该文件加载一行时,我从 PyCharm 控制台收到此错误:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pydev\pydev_run_in_console.py", line 53, in run_file
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "......... .py", line 26, in <module>
    for line in f:
MemoryError
PyDev console: starting.
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32

我使用的是具有 64GB RAM 的 Windows Server 计算机。

我的代码是:

import numpy as np
import json
import sys
import re

idRegEx = re.compile(r".*ID=")
endElRegEx = re.compile(r"'.*")

ratingsFile = sys.argv[1]
tweetsFile = sys.argv[2]
outputFile = sys.argv[3]

tweetsMap = {}
with open(tweetsFile, "r") as f:

    for line in f:
        tweetData = json.loads(line)
        tweetsMap[tweetData["key"]] = tweetData

output = open(outputFile, "w")

with open(ratingsFile, "r") as f:
    header = f.next()

    for line in f:
        topicData = line.split("\t")

        topicKey = topicData[0]
        topicTerms = topicData[1]
        ratings = topicData[2]
        reasons = topicData[3]

        ratings = map(lambda x: int(x.strip().replace("'", "")), ratings.replace("[", "").replace("]", "").split(","))
        ratings = np.array(ratings)

        tweetsMap[topicKey]["ratings"] = ratings.tolist()
        tweetsMap[topicKey]["mean"] = ratings.mean()

        topicMap = tweetsMap[topicKey]

        print topicMap["key"], topicMap["mean"]

        json.dump(topicMap, output, sort_keys=True)
        output.write("\n")

output.close()

错误信息中的第26行指的是

tweetData = json.loads(line)

而第 53 行指的是

json.dump(topicMap, 输出, sort_keys=True)

奇怪的是,我从 GitHub fork 了这段代码,所以我认为它应该可以工作。

最佳答案

您似乎使用的是 32 位版本的 Python:

Python 2.7.14 (...) [MSC v.1500 32 bit (Intel)] on win32

Windows 上每个进程的内存限制为 2GB,因此即使您有足够的 RAM,您也会收到内存错误。如果您不想更改脚本,切换到 64 位版本的 Python 应该可以解决您的问题。

关于python - 使用Python读取json文件中很长的行时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211791/

相关文章:

python - Pygame-子弹和敌人的碰撞,没有 Sprite 或类

python - 如何使用现有版本和 wireshark 编写服务器?

python - Pandas 填补时间序列中缺失的日期

java - 使用 Jackson 将 json 数组转换为某种 Java 表示形式

php - 如何使用input type=file上传json文件

javascript - 当类型设置为 JSON 时如何检查 AJAX 响应字符串

Python:如何优化函数参数?

.net - WCF REST服务不接受.Net 4中的JSON

javascript - 我的 javascript api 不适用于 "Access-Control-Allow-Origin’ 缺失“错误

python - 将列从 float 转换为 int 时收到 KeyError