在Python中统计字符串中特定字符的数量

4
尝试找出在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")

问题在于当我运行这段代码时,对于每个元音字母只得到一个字符,这意味着我的代码实际上并没有按照我想要的方式计算每个元音字母的数量。如果有人能够根据我提供的代码给出修复方法,将不胜感激。

2
从collections模块导入Counter函数。 - Aleksei Maide
2
a_count = sentence.lower().count('a')。 - ekhumoro
你已经接近成功了,唯一忘记的事情是要在输入上进行循环:for letter in sentence: 然后进行计数逻辑。 - georg
1个回答

5

使用来自collections模块的Counter函数计数字母,然后只需迭代计数器,如果该字母是元音字母,则将其计数添加到元音计数器中。

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']))

1
也许你可以将它改为: 如果字母小写后在 ['a', 'e', 'i', 'o', 'u'] 中,则无论它是大写还是小写都不会影响。 - Dana Spitzer Friedlander
@DanaFriedlander 我不确定这是否重要,但就复杂性而言,我非常确定将字母变为小写比查找双倍大小的列表元素要低效。(当然,这只是微小的优化),可读性可能更可取。 - Aleksei Maide

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接