亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嵌套字典替換以前的值 + 鍵而不是附加

嵌套字典替換以前的值 + 鍵而不是附加

江戶川亂折騰 2022-01-05 13:24:38
我正在研究向量空間模型,數據集由 50 個文本文件組成。遍歷它們分解成單詞并將它們保存在字典中?,F在我想使用嵌套字典,如: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 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號