[英]How to find unique values in a large JSON file?
我有兩個大小為data_large(150.1mb)
和data_small(7.5kb)
json文件。 每個文件中的內容類型為[{"score": 68},{"score": 78}]
。 我需要找到每個文件的唯一分數列表。
在處理data_small時 ,我做了以下操作,並且能夠以0.1 secs
查看其內容。
with open('data_small') as f:
content = json.load(f)
print content # I'll be applying the logic to find the unique values later.
但是在處理data_large時 ,我做了以下操作,我的系統被絞死,緩慢,不得不強制關閉它以使其達到正常速度。 打印其內容大約需要2 mins
。
with open('data_large') as f:
content = json.load(f)
print content # I'll be applying the logic to find the unique values later.
在處理大型數據集時如何提高程序的效率?
由於您的json文件不是那么大,您可以一次性將它打開到ram中,您可以獲得所有獨特的值,如:
with open('data_large') as f:
content = json.load(f)
# do not print content since it prints it to stdout which will be pretty slow
# get the unique values
values = set()
for item in content:
values.add(item['score'])
# the above uses less memory compared to this
# since this has to create another array with all values
# and then filter it for unique values
values = set([i['score'] for i in content])
# its faster to save the results to a file rather than print them
with open('results.json', 'wb') as fid:
# json cant serialize sets hence conversion to list
json.dump(list(values), fid)
如果您需要處理更大的文件,那么請尋找可以迭代解析json文件的其他庫。
如果你想在較小的塊中迭代JSON文件以保留RAM,我建議采用下面的方法,根據你的評論,你不想使用ijson來做到這一點。 這只能起作用,因為您的示例輸入數據非常簡單,並且包含一個帶有一個鍵和一個值的字典數組。 對於更復雜的數據,它會變得復雜,我會在那時使用實際的JSON流庫。
import json
bytes_to_read = 10000
unique_scores = set()
with open('tmp.txt') as f:
chunk = f.read(bytes_to_read)
while chunk:
# Find indices of dictionaries in chunk
if '{' not in chunk:
break
opening = chunk.index('{')
ending = chunk.rindex('}')
# Load JSON and set scores.
score_dicts = json.loads('[' + chunk[opening:ending+1] + ']')
for s in score_dicts:
unique_scores.add(s.values()[0])
# Read next chunk from last processed dict.
f.seek(-(len(chunk) - ending) + 1, 1)
chunk = f.read(bytes_to_read)
print unique_scores
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.