相关疑难解决方法(0)

使用python计算文件中的双字节(一对两个单词)

我想用python计算文件中所有bigrams(一对相邻单词)的出现次数.在这里,我正在处理非常大的文件,所以我正在寻找一种有效的方法.我尝试在文件内容上使用带有正则表达式"\ w +\s\w +"的count方法,但它没有被证明是有效的.

例如,假设我要计算文件a.txt中的双字母数,其中包含以下内容:

"the quick person did not realize his speed and the quick person bumped "
Run Code Online (Sandbox Code Playgroud)

对于上面的文件,bigram集和它们的计数将是:

(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
Run Code Online (Sandbox Code Playgroud)

我在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 …
Run Code Online (Sandbox Code Playgroud)

python regex

24
推荐指数
4
解决办法
2万
查看次数

标签 统计

python ×1

regex ×1