【问题标题】:Count specific characters in a string - Python计算字符串中的特定字符 - Python
【发布时间】:2018-03-03 20:31:28
【问题描述】:

试图找出 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")

问题是当我运行它时,我只为每个元音得到一个字符,这意味着我的代码实际上并没有按照我想要的方式计算单个元音。任何人根据我提供的代码输入如何解决此问题将不胜感激

【问题讨论】:

  • 从集合导入计数器
  • a_count = sentence.lower().count('a').
  • 快到了,唯一忘记的是循环输入:for letter in sentence: ,然后是计数逻辑。

标签: python string count character


【解决方案1】:

使用集合模块中的计数器计数字母,然后遍历计数器,如果字母是元音,则将其计数添加到 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']))

【讨论】:

  • 也许你可以把它改成: if letter.lower() in ['a', 'e', 'i', 'o', 'u']: 以防万一不管是不是大写字母
  • @DanaFriedlander 我不确定这是否重要,但在复杂性方面我很确定将字母小写比在列表中查找两倍大小的元素效率低。 (Ofc。这只是一个微优化)和可读性可能更可取。
猜你喜欢
  • 2014-01-30
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
相关资源
最近更新 更多