我有一本形式如下的字典:
d[class name]=(list of files)
前任:
d[earn]=(6,7,4)
其中 6.txt、7.txt 和 4.txt 是属于“earn”类的文件
现在,我需要创建另一个字典 d2 以便:
d2[earn]=(12,3,2,17)
在哪里
- 12是6.txt中出现“earn”这个词的次数,
- 3 是单词“earn”在 7.txt 中出现的次数,
- 4 是单词“earn”在 4.txt 中出现的次数
- 17是三个文件中出现“earn”这个词的次数,即;总和。
这是我的代码:
import collections
import sys
import os
import re
sys.stdout=open('dictionary.txt','w')
from collections import Counter
from glob import glob
folderpath='d:/individual-articles'
counter=Counter()
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+".txt")
filepaths = glob(os.path.join(folderpath,'*.txt'))
def words_generator(fileobj):
for line in fileobj:
for word in line.split():
yield word
word_count_dict = {}
for file in filepaths:
f = open(file,"r")
words = words_generator(f)
for word in words:
if word not in word_count_dict:
word_count_dict[word] = {"total":0}
if file not in word_count_dict[word]:
word_count_dict[word][file] = 0
word_count_dict[word][file] += 1
word_count_dict[word]["total"] += 1
for k in word_count_dict.keys():
for filename in word_count_dict[k]:
if filename == 'total': continue
counter.update(filename)
for word, counts in word_count_dict.items():
print(word, counts['total'])
我需要打印 d2,但我的代码不起作用。