【发布时间】: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