为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

江户川乱折腾 2022-01-05 13:24:38
我正在研究向量空间模型,数据集由 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'...
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超5个赞

您想知道每个单词在每个文件中出现的次数吗?这可以通过 a defaultdictof Counters轻松完成,由 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,

        },

    ...

    }


查看完整回答
反对 回复 2022-01-05
  • 1 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号