python - 如何计算Python中的单词数达到限制?

标签 python python-3.x

我正在编写一个代码,计算包含大约 20,000 个文件的文档中单词出现的频率,我能够获取文档中单词的总体频率,并且 到目前为止我的代码是:

import os
import re
import sys
sys.stdout=open('f2.txt','w')
from collections import Counter
from glob import iglob

def removegarbage(text):
    text=re.sub(r'\W+',' ',text)
    text=text.lower()
    return text

folderpath='d:/articles-words'
counter=Counter()
d=0

for filepath in iglob(os.path.join(folderpath,'*.txt')):
    with open(filepath,'r') as filehandle:
        d+=1

r=round(d*0.1)
for filepath in iglob(os.path.join(folderpath,'*.txt')):
    with open(filepath,'r') as filehandle:
        words=set(removegarbage(filehandle.read()).split())
        if r > counter:
             counter.update()

for word,count in counter.most_common():
    print('{}  {}'.format(word,count))

但是,我想修改我的计数器,并且仅当计数大于 r=0.1*(文件数)时才更新它 简而言之,我想读取在整个文档中出现频率大于文档数量10%的单词。 错误是:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: unorderable types: int() > Counter()

如何修改?

最佳答案

像这样的东西怎么样?

from glob import glob # (instead of iglob)

...

filepaths = glob(os.path.join(folderpath,'*.txt'))

num_files = len(filepaths)

# Add all words to counter
for filepath in filepaths):
    with open(filepath,'r') as filehandle:
        lines = filehandle.read()
        words = removegarbage(lines).split()
        counter.update(words)

# Display most common
for word, count in counter.most_common():

    # Break out if the frequency is less than 0.1 * the number of files
    if count < 0.1*num_files:
        break

    print('{}  {}'.format(word,count))

使用Counter.iteritems():

>>> from collections import Counter
>>> c = Counter()
>>> c.update(['test', 'test', 'test2'])
>>> c.iteritems()
<dictionary-itemiterator object at 0x012F4750>
>>> for word, count in c.iteritems():
...     print word, count
...     
test 2
test2 1

关于python - 如何计算Python中的单词数达到限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139627/

相关文章:

Python 3 使用ElementTree解析xml文件

python - 使用 os.system 从分配给变量的路径启动可执行文件?

python-3.x - Matplotlib 如何为四个 2d 直方图绘制 1 个颜色条

linux - 如何使用 Windows 7 中的 Python 在远程 (Linux) 机器上创建文件

Python短路方法合并链

python - 我希望你的帮助程序每 12 小时自动运行一次

python - 在列表中查找奇数并使用 lambda 函数对它们进行平方

python - 如何在 scikit-learn 中正确计算交叉验证分数?

python - 用于插槽填充的 Webhooks

python - 需要从下拉菜单中单击文本才能更改下拉菜单中的默认选项