python中迭代字典_如何迭代字典python中的所有键?

该博客讲述了如何在Python中迭代字典,并计算字典键(如'Britain')在大量TXT文件中的出现频率。通过遍历文件夹中的TXT文件,使用collections.Counter来统计每个单词在各个文件以及全部文件的总频率。问题在于如何从counter对象中获取特定键在对应文件的频率,并存储到新的字典d2中。
摘要由CSDN通过智能技术生成

我应该计算字典“d”的所有键值在文档“individual articles”中的频率,文档“individual articles”有大约20000个txt文件,文件名为1、2、3、4。。。例如:假设d[Britain]=[5,76289]必须返回属于文档“individual articles”的文件5.txt、76.txt、289.txt中出现Britain的次数,而且我还需要找到它在同一文档中所有文件中的出现频率。在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()

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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值