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

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


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

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

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

 }

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


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'...


江户川乱折腾
浏览 164回答 1
1回答

收到一只叮咚

您想知道每个单词在每个文件中出现的次数吗?这可以通过 a defaultdictof Counters轻松完成,由 collections 模块提供。我认为您的想法是正确的,循环遍历文件,逐行阅读并拆分成单词。这是您需要帮助的计数部分。from collections import defaultdict, Counterfrom string import punctuationfnames = ['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,        },    ...    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python