[英]Count specific characters in a string - Python
嘗試找出Python中允許用戶輸入句子的最佳方法,然后計算該句子中的字符數,以及計算元音的數量。 我希望輸出返回字符總數,再加上A的總數,O的總數,U的總數等。這是到目前為止的代碼:
# prompt for input
sentence = input('Enter a sentence: ')
# count of the number of a/A occurrences in the sentence
a_count = 0
# count of the number of e/E occurrences in the sentence
e_count = 0
# count of the number of i/I occurrences in the sentence
i_count = 0
# count of the number of o/O occurrences in the sentence
o_count = 0
# count of the number of u/U occurrences in the sentence
u_count = 0
# determine the vowel counts and total character count
length=len(sentence)
if "A" or "a" in sentence :
a_count = a_count + 1
if "E" or "e" in sentence :
e_count = e_count + 1
if "I" or "i" in sentence :
i_count = i_count + 1
if "O" or "o" in sentence :
o_count = o_count + 1
if "U" or "u" in sentence :
u_count = u_count + 1
#Display total number of characters in sentence
print("The sentence", sentence, "has", length,"characters, and they are\n",
a_count, " a's\n",
e_count, "e's\n",
i_count, "i's\n",
o_count, "o's\n",
u_count, "u's")
問題是,當我運行此命令時,每個元音只能得到一個字符,這意味着我的代碼實際上並沒有按照我希望的方式對單個元音進行計數。 任何人輸入如何基於我提供的代碼解決此問題,將不勝感激
使用來自集合的計數器模塊對字母計數,然后僅遍歷計數器,如果字母是元音,則將其計數添加到vowel_count。
from collections import Counter
counts = Counter(input('Enter a sentence: '))
vowel_count = 0
for letter in counts:
if letter in ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']:
vowel_count += counts[letter]
例如,要獲取(A,a)的總數,您可以執行以下操作:
print('Count of A\'s is: {}'.format(counts['A'] + counts['a']))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.