![](/img/trans.png)
[英]How to replace first number from each line of a ".txt" file in python?
[英]Python to count number of occurrence of each line, in huge txt file
一個大的 txt 文件有數百萬行,我想計算每一行的出現次數(該行在文件中出現的次數)。
我正在使用的當前解決方案如下。 它有效但非常慢。
這樣做的更好方法是什么? 謝謝!
from collections import Counter
crimefile = open("C:\\temp\\large text_file.txt", 'r', encoding = 'utf-8')
yourResult = [line.strip().split('\n') for line in crimefile.readlines()]
yourResult = sum(yourResult, [])
result = dict((i, yourResult.count(i)) for i in yourResult)
output = sorted((value,key) for (key,value) in result.items())
print (Counter(yourResult))
使用defaultdict
並遍歷行,而不是將所有內容讀取到 memory。
counter = defaultdict(lambda: 0)
with open("C:\\temp\\large text_file.txt", "r", encoding="utf-8") as file:
for line in file:
counter[line.strip()] += 1
counter = dict(counter)
print(counter)
使用timeit
和 10k 行文本進行測試,在我的機器上大約快 40 倍。
我們可以使用單個 for 循環來執行此操作。 我們不必去掉換行符,因為每一行都會有它。
解決方案
counter = {}
with open('filename/path', 'r', encoding='utf-8') as file:
for line in file:
if line not in counter:
counter[line] = 1
else:
counter[line] += 1
print(counter)
時間復雜度
O(n)
您沒有用“非常慢”來限定您的意思。
我有一個包含 250 萬行不同行的文本文件,可以在 ~1.3 秒內處理如下:
from timeit import timeit
FILENAME = '/Volumes/G-Drive/foo.txt'
def get_counts():
d = {}
line_count = 0
with open(FILENAME) as f:
for line in map(str.strip, f):
d[line] = d.get(line, 0) + 1
line_count += 1
key_count = len(d)
print(f'{line_count=}, {key_count=}')
return d
print(timeit(get_counts, number=1))
Output:
line_count=2500000, key_count=2500000
1.2901516660003836
筆記:
您可以使用collections模塊中的 Counter 或 defaultdict,但它們都比此答案中顯示的策略慢。
據我了解所需的功能,您可能不需要刪除這些行。 如果你忽略它,你可以看到大約 12% 的進一步改進
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.