简体   繁体   English

计算字符串中的特定字符-Python

[英]Count specific characters in a string - Python

Trying to figure out the best way in Python to allow a user to input a sentence, and then calculate the number of characters in that sentence, in addition to calculating the number of vowels. 尝试找出Python中允许用户输入句子的最佳方法,然后计算该句子中的字符数,以及计算元音的数量。 I want the output to return the total number of characters, plus the total number of A's, the total number of O's, the total number of U's etc. Here is the code I have so far: 我希望输出返回字符总数,再加上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")

The problem is when I run this I just get one character for each vowel, which means that my code isn't actually counting up the individual vowels the way I want it to. 问题是,当我运行此命令时,每个元音只能得到一个字符,这意味着我的代码实际上并没有按照我希望的方式对单个元音进行计数。 Anyone input how to fix this based on the code I have presented would be appreciated 任何人输入如何基于我提供的代码解决此问题,将不胜感激

Count the letters using Counter from collections module and then just iterate over the counter, if the letter is vowel, add its count to the vowel_count. 使用来自集合的计数器模块对字母计数,然后仅遍历计数器,如果字母是元音,则将其计数添加到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]

For example to get the total count of (A, a)'s you would do: 例如,要获取(A,a)的总数,您可以执行以下操作:

print('Count of A\'s is: {}'.format(counts['A'] + counts['a']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM