在String Python中计算元音

use*_*192 13 python

我正在尝试计算字符串中特定字符的出现次数,但输出错误.

这是我的代码:

inputString = str(input("Please type a sentence: "))
a = "a"
A = "A"
e = "e"
E = "E"
i = "i"
I = "I"
o = "o"
O = "O"
u = "u"
U = "U"
acount = 0
ecount = 0
icount = 0
ocount = 0
ucount = 0

if A or a in stri :
     acount = acount + 1

if E or e in stri :
     ecount = ecount + 1

if I or i in stri :
    icount = icount + 1

if o or O in stri :
     ocount = ocount + 1

if u or U in stri :
     ucount = ucount + 1

print(acount, ecount, icount, ocount, ucount)
Run Code Online (Sandbox Code Playgroud)

如果我输入字母A,输出将是:1 1 1 1 1

iCo*_*dez 15

你想要的可以完全如下:

>>> mystr = input("Please type a sentence: ")
Please type a sentence: abcdE
>>> print(*map(mystr.lower().count, "aeiou"))
1 1 0 0 0
>>>
Run Code Online (Sandbox Code Playgroud)

如果你不认识他们,这里是一个参考map,一个在*.


ins*_*get 9

>>> sentence = input("Sentence: ")
Sentence: this is a sentence
>>> counts = {i:0 for i in 'aeiouAEIOU'}
>>> for char in sentence:
...   if char in counts:
...     counts[char] += 1
... 
>>> for k,v in counts.items():
...   print(k, v)
... 
a 1
e 3
u 0
U 0
O 0
i 2
E 0
o 0
A 0
I 0
Run Code Online (Sandbox Code Playgroud)

  • 而不是`count = {i:0 for i in'aeiouAEIOU'}`你可以做`count = {}.fromkeys('aeiouAEIOU',0)` (3认同)

kyl*_*e k 7

data = str(input("Please type a sentence: "))
vowels = "aeiou"
for v in vowels:
    print(v, data.lower().count(v))
Run Code Online (Sandbox Code Playgroud)


小智 7

def countvowels(string):
    num_vowels=0
    for char in string:
        if char in "aeiouAEIOU":
           num_vowels = num_vowels+1
    return num_vowels
Run Code Online (Sandbox Code Playgroud)

(记住间距s)


Pra*_*mar 5

用一个 Counter

>>> from collections import Counter
>>> c = Counter('gallahad')
>>> print c
Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})
>>> c['a']    # count of "a" characters
3
Run Code Online (Sandbox Code Playgroud)

Counter仅适用于Python 2.7+.应该适用于Python 2.5的解决方案defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for c in s:
...     d[c] = d[c] + 1
... 
>>> print dict(d)
{'a': 3, 'h': 1, 'l': 2, 'g': 1, 'd': 1}
Run Code Online (Sandbox Code Playgroud)


sas*_*llo 5

if A or a in stri意味着if A or (a in stri)哪个是if True or (a in stri)哪个总是True,并且对于你的每个if陈述都是相同的。

你想说的是if A in stri or a in stri

这是你的错误。不是唯一的 - 你并没有真正计算元音,因为你只检查字符串是否包含它们一次。

另一个问题是您的代码远不是执行此操作的最佳方法,请参阅,例如:Count voters from raw input。您会在那里找到一些不错的解决方案,可以轻松地针对您的特定情况采用这些解决方案。我认为如果您详细了解第一个答案,您将能够以正确的方式重写代码。


小智 5

对于任何寻求最简单解决方案的人来说,这是一个

vowel = ['a', 'e', 'i', 'o', 'u']
Sentence = input("Enter a phrase: ")
count = 0
for letter in Sentence:
    if letter in vowel:
        count += 1
print(count)
Run Code Online (Sandbox Code Playgroud)


len*_*doo 5

另一个具有列表理解的解决方案:

vowels = ["a", "e", "i", "o", "u"]

def vowel_counter(str):
  return len([char for char in str if char in vowels])

print(vowel_counter("abracadabra"))
# 5
Run Code Online (Sandbox Code Playgroud)