Как мне вставить текущий словарь в другой в python?
У меня есть дикт по умолчанию, который имеет 3 слоя вложения, который будет использоваться позже для триграммы.
counts = defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:0)))
Затем у меня есть цикл for, который проходит через документ и создает счетчики для каждой буквы (и bicounts и tricounts)
counts[letter1][letter2][letter3] = counts[letter1][letter2][letter3] + 1
Я хочу добавить еще один слой, чтобы я мог указать, является ли буква согласной или гласной.
Я хочу иметь возможность управлять своей биграммой и триграммой по "Согласному против гласного", а не по каждой букве алфавита, но я не знаю, как это сделать.
2 ответа
Я не совсем уверен, что именно вы хотите сделать, но я думаю, что подход с вложенным диктом не так чист, как наличие плоского диктата, в котором вы вводите комбинированную строку символов (т.е. 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})
Предполагая, что вам нужно вести подсчет последовательности гласных и согласных, вы можете просто сохранить другую карту.
Если у вас есть функция 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