Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何跨多个文本文件查找字典中键的频率?_Python_Python 3.x_Machine Learning - Fatal编程技术网

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

Python 如何跨多个文本文件查找字典中键的频率?,python,python-3.x,machine-learning,Python,Python 3.x,Machine Learning,我应该计算文档“individual articles”中所有文件中字典“d”的所有键值的频率 在这里,“个人文章”文档有大约20000个txt文件,文件名为1,2,3,4。。。 例如:假设d[Britain]=[5,76289]必须返回Britain在属于文档“Induvidal articles”的文件5.txt、76.txt、289.txt中出现的次数,并且我需要找到它在同一文档中所有文件中的出现频率。我需要将这些值存储在另一个d2中 同样的例子,, d2必须包含(Britain,2612

我应该计算文档“individual articles”中所有文件中字典“d”的所有键值的频率 在这里,“个人文章”文档有大约20000个txt文件,文件名为1,2,3,4。。。 例如:假设d[Britain]=[5,76289]必须返回Britain在属于文档“Induvidal articles”的文件5.txt、76.txt、289.txt中出现的次数,并且我需要找到它在同一文档中所有文件中的出现频率。我需要将这些值存储在另一个d2中 同样的例子,, d2必须包含(Britain,261200),其中26是文件5.txt、76.txt和289.txt中单词Britain的频率,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"]])
想查看“英国”一词出现的所有文件吗

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

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

那么,我们的代码怎么了?计数是错误的,我想,因为d2在
d2[k]=data.count(k)
,什么是
数据
?对不起,我编辑了它,它的“单词”是0,但我希望所有的键都是0,不仅仅是一个特定的,在本例中是“Britain”,那么我如何为dict中的所有键值运行循环?如何将所有这些值存储在另一个字典中?对于word\u count\u dict中的键值:将迭代字典中的所有键值。如果您希望在另一个字典中使用特殊值,只需将其设置为for循环即可。例如,这就是你如何制作一个只包含总计的字典:totals\u dict={}For key in word\u count\u dict:totals\u dict[key]=word\u count\u dict[key][totals]你可以将该质量的右边变成任何东西。