如何将当前字典嵌入到python中的另一个字典中?

问题描述:

我有一个默认字典,有3层嵌入,稍后将用于三元组。如何将当前字典嵌入到python中的另一个字典中?

counts = defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:0))) 

然后,我有一个for循环,通过一个文件去,并创建每个字母的计数(和bicounts和tricounts)

counts[letter1][letter2][letter3] = counts[letter1][letter2][letter3] + 1 

我想添加另一层,这样我可以,如果指定这封信是一个辅音或一个元音。

我希望能够在辅音与元音之间运行我的bigram和trigram,而不是字母表中的每个字母,但我不知道如何执行此操作。

+0

你能提供你当前的代码吗? – mitoRibo

+0

我不确定我是否理解你的问题......如何不简单地向你的defaultdict添加另一个“图层”来解决问题?你不知道怎么办? –

+1

上帝啊,你真讨厌那个'+ ='对你做了什么?不使用它(尤其是在这里)比“count [letter1] [letter2] [letter3] + = 1”更慢,更可笑冗长/多余! – ShadowRanger

我不确定你想要做什么,但我认为嵌套字典的方法并不像你使用字母组合字符串(即d['ab']而不是d['a']['b'])的字母键盘那样干净。我还加入了代码来检查bigram/trigram是否仅由元音/辅音或混合物组成。

CODE:

from collections import defaultdict 


def all_ngrams(text,n): 
    ngrams = [text[ind:ind+n] for ind in range(len(text)-(n-1))] 
    ngrams = [ngram for ngram in ngrams if ' ' not in ngram] 
    return ngrams 


counts = defaultdict(int) 
text = 'hi hello hi this is hii hello' 
vowels = 'aeiouyAEIOUY' 
consonants = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ' 

for n in [2,3]: 
    for ngram in all_ngrams(text,n): 
     if all([let in vowels for let in ngram]): 
      print(ngram+' is all vowels') 

     elif all([let in consonants for let in ngram]): 
      print(ngram+' is all consonants') 

     else: 
      print(ngram+' is a mixture of vowels/consonants') 

     counts[ngram] += 1 

print(counts) 

OUTPUT:

hi is a mixture of vowels/consonants 
he is a mixture of vowels/consonants 
el is a mixture of vowels/consonants 
ll is all consonants 
lo is a mixture of vowels/consonants 
hi is a mixture of vowels/consonants 
th is all consonants 
hi is a mixture of vowels/consonants 
is is a mixture of vowels/consonants 
is is a mixture of vowels/consonants 
hi is a mixture of vowels/consonants 
ii is all vowels 
he is a mixture of vowels/consonants 
el is a mixture of vowels/consonants 
ll is all consonants 
lo is a mixture of vowels/consonants 
hel is a mixture of vowels/consonants 
ell is a mixture of vowels/consonants 
llo is a mixture of vowels/consonants 
thi is a mixture of vowels/consonants 
his is a mixture of vowels/consonants 
hii is a mixture of vowels/consonants 
hel is a mixture of vowels/consonants 
ell is a mixture of vowels/consonants 
llo is a mixture of vowels/consonants 
defaultdict(<type 'int'>, {'el': 2, 'his': 1, 'thi': 1, 'ell': 2, 'lo': 2, 'll': 2, 'ii': 1, 'hi': 4, 'llo': 2, 'th': 1, 'hel': 2, 'hii': 1, 'is': 2, 'he': 2}) 

假设你需要保持计数元音和辅音你可以简单地保持不同的地图的顺序。

如果你有一个函数is_vowel(letter)返回True如果letter是元音和False如果它是一个辅音,你可以做到这一点。

vc_counts[is_vowel(letter1)][is_vowel(letter2)][is_vowel(letter3)] = \ 
vc_counts[is_vowel(letter1)][is_vowel(letter2)][is_vowel(letter3)] + 1 
+0

非常感谢!太棒了。 –

+0

很棒@KatieTetzloff。如果它解决了你的问题,你可以请upvote并接受答案?谢谢! – cjungel