我有一個成對句子的資料集(英陳述句子及其德語翻譯)。假設我有 WORD1,這是一個英文單詞。我想知道在英陳述句子中出現 WORD1 的一對德陳述句子中出現了哪些德語單詞(以及出現了多少次)。我需要為每個可用的英語單詞執行此操作(我有一個英語單詞串列)。為此,我創建了一個字典,其中鍵都是英語單詞,值是字典,開頭是空的,我想更新它以添加與該英語單詞成對出現的所有德語單詞.
我做的代碼是:
print('Building English dictionary...')
d = dict.fromkeys(words_english, {})
print('Start iterating over samples...')
for sentence_german, sentence_english in zip(data_german, data_english):
sentence_german = sentence_german.split()
sentence_english = sentence_english.split()
for word in sentence_english:
update_dict(word, sentence_german, d)
函式 update_dict 在哪里:
def update_dict(w, sentence, d):
if sentence:
for paired_word in sentence:
if paired_word in d[w].keys():
d[w][paired_word] = d[w][paired_word] 1
else:
d[w][paired_word] = 1
但是,此代碼沒有按我的預期作業。每次呼叫函式 update_dict 時,d 的所有值都會同時更新。例如,如果我執行此代碼(與以前相同,但帶有列印并打破回圈以進行簡化):
print('Building English dictionary...')
d = dict.fromkeys(words_english, {})
print('Start iterating over samples...')
for sentence_german, sentence_english in zip(data_german, data_english):
sentence_german = sentence_german.split()
sentence_english = sentence_english.split()
for word in sentence_english:
print('WORD', word)
print(sentence_german)
update_dict(word, sentence_german, d)
break
break
輸出是:
WORD we
['wir', 'glauben', 'nicht', ',', 'da?', 'wir', 'nur', 'ro', 's', 'inen', 'her', 'au', 'sp', 'ick', 'en', 'sollten', '.']
但是字典 d 現在有這個:
{'wir': 2, 'glauben': 1, 'nicht': 1, ',': 1, 'da?': 1, 'nur': 1, 'ro': 1, 's': 1, 'inen': 1, 'her': 1, 'au': 1, 'sp': 1, 'ick': 1, 'en': 1, 'sollten': 1, '.': 1}
在它的所有價值觀中。為什么不是“我們”的詞更新了?
我還嘗試使用 update_dict 的不同實作(下面的那個),但同樣的問題一直在發生。
def update_dict(w, sentence, d):
if sentence:
for paired_word in sentence:
if paired_word in d[w].keys():
d[w].update({paired_word:(d[w][paired_word] 1)})
else:
d[w].update({paired_word:1})
如果 w 的值只是“我們”,為什么要更新所有鍵(英文單詞)?
uj5u.com熱心網友回復:
因為
d = dict.fromkeys(words_english, {})
{}對所有鍵使用相同的。(fromkeys當值不可變時通常更有用。)
使用字典理解,ala
d = {word: {} for word in words_english}
而是為每個鍵有一個單獨的字典。
更好的是,由于您正在計算出現次數,請使用我們的好朋友defaultdict并Counter從collections模塊中獲取,例如
import collections
d = collections.defaultdict(collections.Counter)
你可以做
d[w][paired_word] = 1
沒有任何if in/update惡作劇,你甚至不需要words_english提前知道。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441375.html
下一篇:遞回搜索映射中的值
