Skip to main content
 首页 » 编程设计

python之嵌套字典替换以前的值+键而不是追加

2024年11月24日9bluestorm

我正在研究向量空间模型,数据集由 50 个文本文件组成。遍历它们拆分成单词并将它们保存在字典中。现在我想像这样使用嵌套字典:

dictionary = { {someword: {Doc1:23},{Doc21:2},{Doc34:3}}, 
{someword: {Doc1:23},{Doc21:2},{Doc34:3}}, 
{someword: {Doc1:23},{Doc21:2},{Doc34:3}} 
 } 

但是当我运行我的程序时,它不仅会替换文档,而且不会通过添加“someword”在特定文档中出现的次数来计算频率。

for iterator in range(1, 51): 
    f = open(directory + str(iterator) + ext, "r") 
    for line in f.read().lower().split(): 
        line = getwords(line) 
        for word in line: 
            if check(word, stopwords) == 0: 
                if existence(word, terms, iterator) != 1: 
                    terms[word] = {} 
                    terms[word]["Doc"+str(iterator)] = 1 
                else: 
                    terms[word]["Doc"+str(iterator)] = int(terms[word]["Doc"+str(iterator)]) + 1 
 
    f.close() 
 

存在函数是:

def existence(tok, diction, iteration): 
    if tok in diction: 
        temp = "Doc"+str(iteration) 
        if temp in diction: 
            return 1 
        else: 
            return 0 
    else: 
        return 0 
 

结果有点像这样。

{'blunder': {'Doc1': 1}, 'by': {'Doc50': 1}, 'anton': {'Doc27': 1}, 'chekhov': {'Doc27': 1}, 'an': {'Doc50': 1}, 'illustration': {'Doc48': 1}, 'story': {'Doc48': 1}, 'author': {'Doc48': 1}, 'portrait'... 

请您参考如下方法:

您想知道每个单词在每个文件中出现了多少次吗?这很容易通过 Counter 的 defaultdict 实现,由 collections 模块提供。

我认为您的想法是正确的,遍历文件,逐行阅读并拆分成单词。这是您需要帮助的计数部分。

from collections import defaultdict, Counter 
from string import punctuation 
 
fnames = ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt'] 
 
word_counter = defaultdict(Counter) 
for fname in fnames: 
    with open(fname, 'r') as txt: 
        for line in txt: 
            words = line.lower().strip().split() 
            for word in words: 
                word = word.strip(punctuation) 
                if word: 
                    word_counter[word][fname] += 1 

word_counter 中的数据看起来像这样:

{ 
    'within': { 
        '1.txt': 2, 
        }, 
    'we': { 
        '1.txt': 3, 
        '2.txt': 2, 
        '3.txt': 2, 
        '4.txt': 2, 
        '5.txt': 4, 
        }, 
    'do': { 
        '1.txt': 7, 
        '2.txt': 8, 
        '3.txt': 8, 
        '4.txt': 6, 
        '5.txt': 5, 
        }, 
    ... 
    }