如何在python中将当前词典嵌套到另一个词典中?

2024-09-21 09:56:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个默认的dict,它有3层嵌入,稍后将用于一个trigram。你知道吗

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

然后,我有一个for循环,它遍历一个文档并创建每个字母的计数(以及bicounts和tricounts)

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

我想添加另一层,以便可以指定字母是辅音还是元音。你知道吗

我想能够在辅音和元音上运行我的二元图和三元图,而不是在字母表的每个字母上运行,但我不知道如何做到这一点。你知道吗


Tags: lambda文档for字母trigramdict计数元音
2条回答

假设你需要保持元音和辅音序列的计数,你可以简单地保持一个不同的映射。你知道吗

如果你有一个函数is_vowel(letter),如果True是元音,如果letter是辅音,你可以这样做。你知道吗

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

我不确定您到底想做什么,但我认为嵌套dict方法并不像使用平面dict那样干净,在平面dict中,您可以通过组合字符串(即d['ab']而不是d['a']['b'])进行键控。我还输入了代码来检查二元/三元结构是由元音/辅音组成还是由一个混合词组成。你知道吗

代码:

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)

输出:

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})

相关问题 更多 >

    热门问题