【发布时间】:2017-10-25 10:15:37
【问题描述】:
我有两个相当大的文件,JSON(185,000 行)和 CSV(650,000)。我需要遍历 JSON 文件中的每个 dict,然后在其中遍历 part_numbers 中的每个部分,并比较它以获取 CSV 中该部分所在位置的前三个字母。
由于某种原因,我很难正确地做到这一点。我的脚本的第一个版本太慢了,所以我正在尝试加快速度
JSON 示例:
[
{"category": "Dryer Parts", "part_numbers": ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR"], "parent_category": "Dryers"},
{"category": "Washer Parts", "part_numbers": ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR"], "parent_category": "Washers"},
{"category": "Sink Parts", "part_numbers": ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR"], "parent_category": "Sinks"},
{"category": "Other Parts", "part_numbers": ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR"], "parent_category": "Others"}
]
CSV:
WCI|ABC
WPL|DEF
BSH|GHI
WCI|JKL
结束的字典如下所示:
{"category": "Other Parts",
"part_numbers": ["WCIABC","WPLDEF","BSHGHI","JKLWCI"...]}
这是我到目前为止所做的一个示例,它在if (part.rstrip() == row[1]): 返回IndexError: list index out of range:
import csv
import json
from multiprocessing import Pool
def find_part(item):
data = {
'parent_category': item['parent_category'],
'category': item['category'],
'part_numbers': []
}
for part in item['part_numbers']:
for row in reader:
if (part.rstrip() == row[1]):
data['part_numbers'].append(row[0] + row[1])
with open('output.json', 'a') as outfile:
outfile.write(' ')
json.dump(data, outfile)
outfile.write(',\n')
if __name__ == '__main__':
catparts = json.load(open('catparts.json', 'r'))
partfile = open('partfile.csv', 'r')
reader = csv.reader(partfile, delimiter='|')
with open('output.json', 'w+') as outfile:
outfile.write('[\n')
p = Pool(50)
p.map(find_part, catparts)
with open('output.json', 'a') as outfile:
outfile.write('\n]')
【问题讨论】:
-
那时
row是什么?你之前处理了多少行?此外,您能否发布 minimal 代码(根据发布指南),或者该文件是否读取了问题的重要部分? -
文件读取并不是真正的问题。更多的是关于如何有效地做到这一点。你还需要什么代码?
-
没有更多代码... 更少。但是,我想我在无法运行代码的情况下发现了它。
-
当我使用示例输入文件运行您的代码时,我在
'parent_category': item['parent_category'],函数中的'parent_category': item['parent_category'],行上得到一个KeyError: 'parent_category'— 所以我无法重现“不正确的索引错误”问题提到。 -
@martineau 对不起!我正在使用一个忘记包含在 json 示例中的密钥。它不见了
parent_category
标签: python json python-3.x csv multiprocessing