1 回答

TA贡献1821条经验 获得超5个赞
您想知道每个单词在每个文件中出现的次数吗?这可以通过 a defaultdictof Counters轻松完成,由 collections 模块提供。
我认为您的想法是正确的,循环遍历文件,逐行阅读并拆分成单词。这是您需要帮助的计数部分。
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
里面的数据看起来像这样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,
},
...
}
添加回答
举报