我不确定您到底想做什么,但我认为嵌套 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})