我想使用python统计文件中所有相邻单词对的出现次数(即bigrams),由于我处理的是非常大的文件,所以我正在寻找一种高效的方法。我尝试在文件内容上使用带有正则表达式"\w+\s\w+" 的count方法,但它并不高效。
例如,假设我想从文件a.txt中计算bigrams的数量,该文件具有以下内容:
这个示例是这样的:
例如,假设我想从文件a.txt中计算bigrams的数量,该文件具有以下内容:
"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 对象的示例,用于计算单词数量。它还使用了正则表达式方法。这个示例是这样的:
>>> # 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)]
我想知道是否可以使用计数器对象来获取二元组的计数。欢迎使用计数器对象或正则表达式以外的任何方法。