python - 如何跨多个文本文件查找字典中键的频率?

标签 python python-3.x machine-learning

我应该计算文档“individual-articles”中所有文件中字典“d”的所有键值的频率 这里,文档“individual-articles”大约有20000个txt文件,文件名为1,2,3,4... 例如:假设 d[Britain]=[5,76,289] 必须返回英国出现在属于文档“个人文章”的文件 5.txt,76.txt,289.txt 中的次数,而且我还需要找出它在同一文档中所有文件中的频率。我需要将这些值存储在另一个 d2 中 对于同一个例子, d2 必须包含 (Britain,26,1200),其中 26 是单词 Britain 在文件 5.txt、76.txt 和 289.txt 中的频率,1200 是单词 Britain 在所有文件中的频率。 我是一个Python新手,我尝试的很少!请帮忙!!

import collections
import sys
import os
import re
sys.stdout=open('dictionary.txt','w')
from collections import Counter
from glob import glob
def removegarbage(text):
    text=re.sub(r'\W+',' ',text)
    text=text.lower()
    sorted(text)
    return text


folderpath='d:/individual-articles'
counter=Counter()


filepaths = glob(os.path.join(folderpath,'*.txt'))


d2={}
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)

for filepath in filepaths:
    with open(filepath,'r') as filehandle:
        lines = filehandle.read()
        words = removegarbage(lines).split()
        for k in d.keys():
            d2[k] = words.count(k)

for i in d2.items():
    print(i)

最佳答案

嗯,我不太确定文档“X”中的所有文件是什么意思,但我认为它类似于书中的页面。有了这个解释,我会尽力以最简单的方式存储数据。将数据放入易于操作的位置可以提高以后的效率,因为您始终可以添加用于完成所需输出的方法和类型。

由于您正在查看的主键似乎是关键字,因此我将使用此结构创建一个嵌套的 python 字典

dict = (keyword:{file:count})

一旦采用这种形式,您就可以非常轻松地对数据进行任何类型的操作。

要创建这个字典,

import os
# returns the next word in the file
def words_generator(fileobj):
    for line in fileobj:
        for word in line.split():
            yield word
word_count_dict = {}
for dirpath, dnames, fnames in os.walk("./"):
    for file in fnames:
        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

这将创建一个易于解析的字典。

想要英国的总字数吗?

word_count_dict["Britain"]["total"]

想知道英国出现在文件 74.txt 和 75.txt 中的次数吗?

sum([word_count_dict["Britain"][file] if file in word_count_dict else 0 for file in ["74.txt", "75.txt"]])

想要查看包含“British”一词的所有文件吗?

[file for key in word_count_dict["Britain"]]

您当然可以编写通过简单调用来执行这些操作的函数。

关于python - 如何跨多个文本文件查找字典中键的频率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17186253/

相关文章:

python - GStreamer 警告 : Cannot query video position: status=0, 值=-1,持续时间=-1

python-3.x - 类型错误 : POST data should be bytes or an iterable of bytes. 不能是 str

python - 逻辑回归: objects are not aligned

machine-learning - 保存/重用基于 doc2vec 的模型进行进一步预测

machine-learning - NaiveBayes 分类器 : Do I have to concatenate all files of one class?

python - Emit() 向不同类发出信号不起作用

python - CsvItemExporter 的 Scrapy 自定义 CSV header

python - C 返回具有错误值的 numpy 数组

Python ffmpeg子进程: Broken pipe

python - 标记列表中的重复项