【发布时间】:2012-09-11 09:48:10
【问题描述】:
我想使用 python 计算文件中所有二元组(相邻单词对)的出现次数。在这里,我正在处理非常大的文件,因此我正在寻找一种有效的方法。我尝试在文件内容上使用带有正则表达式 "\w+\s\w+" 的计数方法,但它并没有被证明是有效的。
例如假设我想计算文件 a.txt 中的二元组数,该文件具有以下内容:
"the quick person did not realize his speed and the quick person bumped "
对于上述文件,二元组及其计数将为:
(the,quick) = 2
(quick,person) = 2
(person,did) = 1
(did, not) = 1
(not, realize) = 1
(realize,his) = 1
(his,speed) = 1
(speed,and) = 1
(and,the) = 1
(person, bumped) = 1
我在 Python 中遇到了一个 Counter 对象的示例,它用于计算 unigrams(单个单词)。它还使用正则表达式方法。
示例如下:
>>> # Find the ten most common words in Hamlet
>>> import re
>>> from collections import Counter
>>> words = re.findall('\w+', open('a.txt').read())
>>> print Counter(words)
以上代码的输出是:
[('the', 2), ('quick', 2), ('person', 2), ('did', 1), ('not', 1),
('realize', 1), ('his', 1), ('speed', 1), ('bumped', 1)]
我想知道是否可以使用 Counter 对象来获取二元数。 除了 Counter 对象或正则表达式之外的任何方法也将不胜感激。
【问题讨论】:
-
粘贴有问题的示例文本。
-
你必须处理多行还是每个文件的文本都在一行?
-
Counting bi-gram frequencies 的可能重复项
-
是的,mhawke,文件中的文本是单行的。
-
Ashwini Chaudhary,我在上面的代码标签中包含了示例文本。给您带来的不便深表歉意!