1 回答

TA貢獻1821條經(jīng)驗 獲得超5個贊
您想知道每個單詞在每個文件中出現(xiàn)的次數(shù)嗎?這可以通過 a defaultdictof Counters輕松完成,由 collections 模塊提供。
我認(rèn)為您的想法是正確的,循環(huán)遍歷文件,逐行閱讀并拆分成單詞。這是您需要幫助的計數(shù)部分。
from collections import defaultdict, Counter
from string import punctuation
fnames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']
word_counter = defaultdict(Counter)
for fname in fnames:
with open(fname, 'r') as txt:
for line in txt:
words = line.lower().strip().split()
for word in words:
word = word.strip(punctuation)
if word:
word_counter[word][fname] += 1
里面的數(shù)據(jù)看起來像這樣word_counter:
{
'within': {
'1.txt': 2,
},
'we': {
'1.txt': 3,
'2.txt': 2,
'3.txt': 2,
'4.txt': 2,
'5.txt': 4,
},
'do': {
'1.txt': 7,
'2.txt': 8,
'3.txt': 8,
'4.txt': 6,
'5.txt': 5,
},
...
}
添加回答
舉報