簡體   English   中英

如何遍歷字典python中的所有鍵?

[英]how to iterate over all keys in dictionary python?

我應該計算“個人文章”文檔中所有文件中字典“ d”的所有鍵值的出現頻率。在這里,“個人文章”文檔中大約有20000個txt文件,文件名是1,2, 3,4 ...例如:假設d [Britain] = [5,76,289]必須返回英國在屬於“工業物品”文檔的文件5.txt,76.txt,289.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()


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 k in word_count_dict.keys():
    for count in counter.most_common():
        print('{}  {}'.format(word_count_dict[k],count))

我如何僅在那些是該鍵值的字典元素的文件中找到英國的出現頻率?

對於同一示例,我需要將這些值存儲在另一個d2中,d2必須包含

(英國26,1200)(西班牙52,6795)(法國45,568)

其中26是文件5.txt,76.txt和289.txt中不列顛單詞的出現頻率,而1200是所有文件中不列顛單詞的出現頻率。 西班牙和法國也是如此。

我在這里使用counter,我認為這是缺陷,因為到目前為止,除我的最終循環外,其他一切都正常!

我是python新手,我嘗試了很少! 請幫忙!!

word_count_dict["Britain"]是一本常規詞典。 只需循環:

for filename in word_count_dict["Britain"]:
    if filename == 'total': continue
    print("Britain appears in {} {} times".format(filename, word_count_dict["Britain"][filename]))

或使用以下方法檢索所有密鑰:

word_count_dict["Britain"].keys()

請注意,該詞典中total一個特殊鍵。

可能是您的縮進已關閉,但看來您沒有正確計算文件條目:

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        

如果以前沒有在每個單詞的詞典中看到file則只會計數( += 1 )個單詞; 將其更正為:

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

for word, counts in word_count_dict.iteritems():
    print('Total counts for word {}: '.format(word, counts['total']))
    for filename, count in counts.iteritems():
        if filename == 'total': continue
        print("{} appears in {} {} times".format(word, filename, count))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM