Python中1Gb文本文件的字频率计算

时间:2013-02-03 15:51:16

标签: python word-frequency

我正在尝试计算大小为1.2 GB的文本文件的字频率,大约为2.03亿字。我使用以下Python代码。但它给了我一个内存错误。对此有什么解决方案吗?

这是我的代码:

import re
# this one in honor of 4th July, or pick text file you have!!!!!!!
filename = 'inputfile.txt'
# create list of lower case words, \s+ --> match any whitespace(s)
# you can replace file(filename).read() with given string
word_list = re.split('\s+', file(filename).read().lower())
print 'Words in text:', len(word_list)
# create dictionary of word:frequency pairs
freq_dic = {}
# punctuation marks to be removed
punctuation = re.compile(r'[.?!,":;]') 
for word in word_list:
    # remove punctuation marks
    word = punctuation.sub("", word)
    # form dictionary
    try: 
        freq_dic[word] += 1
    except: 
        freq_dic[word] = 1

print 'Unique words:', len(freq_dic)
# create list of (key, val) tuple pairs
freq_list = freq_dic.items()
# sort by key or word
freq_list.sort()
# display result
for word, freq in freq_list:
    print word, freq

这是错误,我收到了:

Traceback (most recent call last):
  File "count.py", line 6, in <module>
    word_list = re.split('\s+', file(filename).read().lower())
  File "/usr/lib/python2.7/re.py", line 167, in split
    return _compile(pattern, flags).split(string, maxsplit)
MemoryError

2 个答案:

答案 0 :(得分:14)

问题从这里开始:

file(filename).read()

这会将整个文件读入一个字符串。相反,如果您逐行或逐块处理文件,则不会遇到内存问题。

with open(filename) as f:
    for line in f:

您还可以使用collections.Counter来计算单词的频率。

In [1]: import collections

In [2]: freq = collections.Counter()

In [3]: line = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod'

In [4]: freq.update(line.split())

In [5]: freq
Out[5]: Counter({'ipsum': 1, 'amet,': 1, 'do': 1, 'sit': 1, 'eiusmod': 1, 'consectetur': 1, 'sed': 1, 'elit,': 1, 'dolor': 1, 'Lorem': 1, 'adipisicing': 1})

再计算一些词,

In [6]: freq.update(line.split())

In [7]: freq
Out[7]: Counter({'ipsum': 2, 'amet,': 2, 'do': 2, 'sit': 2, 'eiusmod': 2, 'consectetur': 2, 'sed': 2, 'elit,': 2, 'dolor': 2, 'Lorem': 2, 'adipisicing': 2})

collections.Counterdict的子类,因此您可以按照您已熟悉的方式使用它。此外,它还有一些有用的计数方法,例如most_common

答案 1 :(得分:5)

问题是您正在尝试将整个文件读入内存。 解决方案是逐行读取文件,计算每行的单词,并对结果求和。