【发布时间】:2013-06-19 16:54:20
【问题描述】:
所以基本上,我有一本字典 d,它从文本文件“topics.txt”中读取 “topics.txt”,具有以下模式的行:
1~英国~意大利~印度
2~西班牙~土耳其
3~法国
4~埃及~中国~日本~冰岛
等等..
这里,数字对应于文件“1.txt”、“2.txt”等等……属于文档“individual-articles”
在字典“d”中,我将文档“individual-articles”的所有文件分类为topics.txt中给出的单词的类
所以,带有键值的字典“d”说“英国”、“法国”和“西班牙”的形式是:
(Britain,[1,76,289]) 其中文件 1.txt,76.txt,289.txt 属于“英国”类
(Spain,[2,8]) 其中文件 2.txt,8.txt 属于“西班牙”类
(france,[3,99,12,43]) 其中文件 3.txt,99.txt,12.txt,43.txt 属于“法国” 等等..
现在我正在创建另一个字典“word_count_dict”,其中包含类名和“类”在 IT 文件中出现的次数,可以从“d”中获取。
例如: word_count_dict 必须有:
(Britain,236) 其中 236 是“Britain”一词在文件 1.txt,76.txt,289.txt 中出现的次数
(France,56) 其中 56 是“法国”一词在文件 3.txt,99.txt,12.txt,43.txt 中出现的次数
等等……
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'])
到目前为止,我已经尝试过这段代码,但我不认为正在检查 d 中那个特定键的文件!
output:
d2=(["Britain",45],["France",56],["Spain",89],.....)
其中 45 是“英国”一词在文件中出现的次数:1.txt,76.txt,289.txt
56 是文件中单词“France”的出现次数: 3.txt,99.txt,12.txt,43.txt
没有在文件 1.txt、76.txt、289.txt 中检查单词“britain”出现的频率,这些文件可以从字典“d”中获得,而是我的程序检查所有文件!
【问题讨论】:
-
请用文本文件中的示例数据阐明您的前提。
-
您的意见是什么?你得到什么输出?您的预期输出是什么?
-
我收到一个错误:回溯(最近一次调用最后一次):文件“C:\Python33\access_dict2.py”,第 41 行,在
word_count_dict[word][file]=0 KeyError : '英国' -
我想打印 word_count_dict!
-
您能否在您的问题中使用正确的格式以使问题更易于理解?或者我只是厌倦了接受阅读你的必要努力......
标签: python dictionary python-3.x machine-learning