簡體   English   中英

Python-有效地從大型json文件中找到唯一值

[英]Python- find the unique values from a large json file efficienctly

我有一個json文件data_large ,大小為150.1MB。 文件內的內容的類型為[{"score": 68},{"score": 78}] 我需要找到每個項目的唯一分數列表。

這就是我在做什么:-

import ijson  # since json file is large, hence making use of ijson

f = open ('data_large')
content = ijson.items(f, 'item') # json loads quickly here as compared to when json.load(f) is used.
print set(i['score'] for i in content) #this line is actually taking a long time to get processed.

我可以使print set(i['score'] for i in content)效率更高print set(i['score'] for i in content) 目前需要201秒才能執行。 可以提高效率嗎?

這將為您提供一組唯一的分數值(僅)(以整數為單位)。 您需要150 MB的可用內存。 它使用re.finditer()進行解析,這比json解析器(在我的計算機上)快大約三倍。

import re
import time
t = time.time()
obj = re.compile('{.*?: (\d*?)}')
with open('datafile.txt', 'r') as f:
    data = f.read()
s = set(m.group(1) for m in obj.finditer(data))
s = set(map(int, s))
print time.time() - t

使用re.findall()似乎也比json解析器快大約三倍,它消耗約260 MB:

import re
obj = re.compile('{.*?: (\d*?)}')
with open('datafile.txt', 'r') as f:
    data = f.read()
s = set(obj.findall(data))

我認為沒有什么辦法可以改善很多事情。 最慢的部分可能只是在某些時候您需要解析整個JSON文件這一事實。 無論你做這一切在前面(與json.load )或一點一點地(消耗來自發電機時ijson.items ),整個文件需要最終處理。

使用ijson的優點是,在任何給定時間,您只需要在內存中存儲少量數據即可。 對於具有大約100兆字節數據的文件來說,這可能無關緊要,但是如果您的數據文件增長到千兆字節或更大,這將是非常大的事情。 當然,這也可能取決於您所運行的硬件。 如果您的代碼要在內存有限的嵌入式系統上運行,那么限制內存使用就顯得尤為重要。 另一方面,如果要在具有大量可用RAM的高性能服務器或工作站上運行,則可能沒有任何理由推遲。

因此,如果您不希望數據過大(相對於系統的RAM容量),則可以嘗試進行測試以查看是否從一開始就使用json.load讀取了整個文件,然后使用set更快。 我認為沒有其他明顯的捷徑。

在我的系統上,下面的簡單代碼可在18秒內處理10,000,000個分數(139兆字節)。 那太慢了嗎?

#!/usr/local/cpython-2.7/bin/python

from __future__ import print_function

import json  # since json file is large, hence making use of ijson

with open('data_large', 'r') as file_:
    content = json.load(file_)
    print(set(element['score'] for element in content))

嘗試使用一套

set([x['score'] for x in scores])

例如

>>> scores = [{"score" : 78}, {"score": 65} , {"score" : 65}]
>>> set([x['score'] for x in scores])
set([65, 78])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM