标题说明了一切! 我正在尝试在我创建的菜单中创建“显示统计信息”选项。输入一句话后会显示以下内容。例如: 字符串分析: 6个字 26 个字符 9 个元音 17 个辅音。 我已经制作了整个单词和字符计数器,现在我需要做元音和辅音,有人可以帮助我吗?非常感谢您的支持!
到目前为止我得到了什么:
def displayst():
print()
print("You said the following:")
time.sleep(1)
length = str(input("Please enter your sentence: "))
word = dis(length)
lengths = diss(length)
vowel = disv(length)
print(length)
time.sleep(1)
print()
print("String Analysis:",'\n', word, "Words",'\n', lengths, "Characters",'\n',vowel,"Vowels",'\n')
again()
元音 = disv(length) 是我需要完成的,如果你能帮助解决辅音,那就太好了!如果不是,我主要需要将元音作为辅音来完成,我想我可以尝试一下哈哈。
然后在我的 disv(length) 中:
vowels = 'aeiou'
count = {}.fromkeys(vowels,0)
for char in length:
if char in count:
count[char] += 1
print(count)
这太疯狂了,老实说我不知道我要去哪里,哈哈。 请大家帮忙加油。
最佳答案
如果您想要计数,请使用 Counter 字典:
from collections import Counter
inp = input("Please enter your sentence: ").lower()
cn = Counter(inp)
vowels = {v: cn[v] for v in "aeiou" if v in cn}
cons = {c: cn[c] for c in "bcdfghjklmnpqrstvwxyz" if c in cn}
如果您想要总计数,只需将值相加即可:
print(sum(vowels.values()))
print(sum(cons.values()))
如果您只想要总和:
vowels = sum(cn[v] for v in "aeiou")
cons = sum(cn[c] for c in "bcdfghjklmnpqrstvwxy")
关于python - 如何在Python中创建元音计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29568889/