我有代码来计算文件中的单词。它适用于小于500 MB的小文件。我必须在开始计数之前将整个文件保留在内存中,否则计数中会出错。此代码读取文件并将其存储到RAM中,然后对其进行处理。如果我逐行阅读,则计数中会出现错误(readline()
)。
import collections
import codecs
from collections import Counter
with io.open('Prabhodhanam.txt', 'r', encoding='utf8') as infh:
words =infh.read().split()
with open('file.txt', 'wb') as f:
for word, count in Counter(words).most_common(10000000):
f.write(u'{} {}\n'.format(word, count).encode('utf8'))
当文件很大时会产生
Memory error
当我们使用read line()时Counter()
倾向于计算行中的单词而不是整个文件
如何计算单词而不将整个文件存储到内存中?
答案 0 :(得分:1)
请检查此代码。 我不知道这是否有帮助。
def filePro(filename):
f=open(filename,'r')
wordcount=0
for lines in f:
f1=lines.split()
wordcount=wordcount+len(f1)
f.close()
print 'word count:', str(wordcount)
filePro(raw_input("enter file name:"))
答案 1 :(得分:1)
您不必将整个文件存储在内存中。你可以逐行计算单词(但是当然你不能在每一行之后重置计数器,所以列表理解在这里不起作用。)
import collections
counter = collections.Counter()
with open('Prabhodhanam.txt', 'r', encoding='utf8') as infh:
for line in infh:
counter.update(line.strip().split())
with open('file.txt', 'wb') as f:
for word, count in counter.most_common(10000000):
f.write(u'{} {}\n'.format(word, count).encode('utf8'))