フォルダー内の複数のファイル内の単語の頻度を見つけようとしています。ファイル内に単語が見つかった場合は、単語のカウントを 1 増やす必要があります。例: ファイル 1 で読み取られた場合、「終わりが良ければすべて良し」という行は、「よく」のカウントを 2 ではなく 1 ずつインクリメントする必要があります。 2になる
重複を含めずにカウンターをインクリメントする必要がありますが、私のプログラムはそれを考慮していないので、助けてください!!
import os
import re
import sys
sys.stdout=open('f1.txt','w')
from collections import Counter
from glob import glob
def removegarbage(text):
text=re.sub(r'\W+',' ',text)
text=text.lower()
sorted(text)
return text
def removeduplicates(l):
return list(set(l))
folderpath='d:/articles-words'
counter=Counter()
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()
cwords=removeduplicates(words)
counter.update(cwords)
# 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))
並べ替えと重複の削除の手法を試しましたが、それでもうまくいきません!