我想解析一个巨大的日志文件(大约5 GB)。在Python中解析巨大的日志文件
我只想解析前500,000行,我不想将整个文件读入内存。
基本上,我想要做的是下面的代码是做的,但用while
循环代替for
循环和if
有条件。我也想确保不会将整个文件读入内存。
import re
from collections import defaultdict
FILE = open('logs.txt', 'r')
count_words=defaultdict(int)
import pickle
i=0
for line in FILE.readlines():
if i < 500000:
m = re.search('key=([^&]*)', line)
count_words[m.group(1)]+=1
i+=1
csv=[]
for k, v in count_words.iteritems():
csv.append(k+","+str(v))
print "\n".join(csv)