【问题标题】:word frequency calculation in multiple files [duplicate]多个文件中的词频计算[重复]
【发布时间】:2013-06-16 21:02:11
【问题描述】:

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

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()

for filepath in iglob(os.path.join(folderpath,'*.txt')):
    with open(filepath,'r') as filehandle:
        counter.update(removegarbage(filehandle.read()).split())

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

但是,我想修改我的计数器,并为每个文件只更新一次,即 count 必须对应于 0 或 1,以便在文档中的文件中出现或不出现。 例如: “little”这个词在file1中出现了3次,在file45中出现了8次, 因此,计数值必须是 2 而不是 11 但我现在的代码显示 11。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    使用sets:

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

    set 仅包含唯一值:

    >>> strs = "foo bat foo"
    >>> set(strs.split())
    set(['bat', 'foo'])
    

    使用collections.Counter的示例:

    >>> c = Counter()
    >>> strs = "foo bat foo"
    >>> c.update(set(strs.split()))
    >>> strs = "foo spam foo"
    >>> c.update(set(strs.split()))
    >>> c
    Counter({'foo': 2, 'bat': 1, 'spam': 1})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 2011-04-25
      • 2017-05-07
      • 1970-01-01
      相关资源
      最近更新 更多