0

ドキュメント「individual-articles」内のすべてのファイルで、辞書「d」のすべてのキー値の頻度をカウントすることになっています。ここでは、ドキュメント「individual-articles」には、ファイル名が 1、2、 3,4... 例: d[Britain]=[5,76,289] は、文書「個々の記事」に属するファイル 5.txt,76.txt,289.txt に英国が出現する回数を返さなければならないとします。 、また、同じドキュメント内のすべてのファイルでその頻度を見つける必要があります。同じ例では、これらの値を別の d2 に保存する必要があります。d2 には (Britain,26,1200) が含まれている必要があります。ここで、26 はファイル 5.txt,76.txt および 289.txt 内のブリテンという単語の頻度であり、1200 はすべてのファイルでのブリテンという単語の頻度。私はPythonの初心者で、ほとんど試していません! 助けてください!!

import collections
import sys
import os
import re
sys.stdout=open('dictionary.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


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


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


d2={}
with open('topics.txt') as f:
    d = collections.defaultdict(list)
    for line in f:
        value, *keys = line.strip().split('~')
        for key in filter(None, keys):
            d[key].append(value)

for filepath in filepaths:
    with open(filepath,'r') as filehandle:
        lines = filehandle.read()
        words = removegarbage(lines).split()
        for k in d.keys():
            d2[k] = words.count(k)

for i in d2.items():
    print(i)
4

1 に答える 1