0

所以基本上,我有一个字典 d,它从文本文件“topics.txt”“topics.txt”中读取,具有以下模式的行:

1~英国~意大利~印度

2~西班牙~土耳其

3~法国

4~埃及~中国~日本~冰岛

等等..

这里,数字对应于文件“1.txt”、“2.txt”等等……属于文档“个人文章”

在字典“d”中,我将文档“individual-articles”的所有文件分类为topics.txt中给出的单词的类

因此,带有键值的字典“d”说“英国”、“法国”和“西班牙”的形式是:

(Britain,[1,76,289]) 其中文件 1.txt,76.txt,289.txt 属于“英国”类

(Spain,[2,8]) 其中文件 2.txt,8.txt 属于“西班牙”类

(法国,[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 是文件中“法国”一词的出现次数:3.txt,99.txt,12.txt,43.txt

没有在文件 1.txt、76.txt、289.txt 中检查“英国”一词的出现频率,这可以从字典“d”中获得,而是我的程序检查所有文件!

4

1 回答 1

0
def word_count_dict(fname):
    from os.path import isfile
    if isfile(fname):
        d={}
        with open(fname) as fi:
            for line in fi:
                entries=line.split('~')
                for elem in entries[1:]:
                    d[elem]=d.get(elem,[])+[entries[0]]
        for k in d:
            print (k,len(d[k]))

word_count_dict('topics.txt')

I think this should work.

于 2013-11-25T00:25:11.563 回答