Python中统计字符串中的元音字母数量

17

我想要统计字符串中特定字符的出现次数,但结果不正确。

这是我的代码:

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)

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


stri 声明在哪里?你是如何生成输出的?输入是什么? - Thomas Upton
1
要计算字符串中的字符数,请使用count方法:'aabccc'.count('c') - dawg
可能是统计句子中元音字母数量并显示最频繁的字母的重复问题。 - inspectorG4dget
1
你忘记了 y - beruic
这个回答解决了你的问题吗? [如何测试多个变量是否等于一个值?] (https://dev59.com/f2Up5IYBdhLWcg3wtZE0) - Tomerikoo
29个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
26

你想要的可以很简单地完成,就像这样:

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

如果您不熟悉它们,请参考map*


17
def countvowels(string):
    num_vowels=0
    for char in string:
        if char in "aeiouAEIOU":
           num_vowels = num_vowels+1
    return num_vowels

(记住间距 s)


10
>>> 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

4
可以使用counts={}.fromkeys('aeiouAEIOU',0)来替代counts = {i:0 for i in 'aeiouAEIOU'}。这将创建一个以元音字母为键,值为0的空字典。 - dawg

10
data = str(input("Please type a sentence: "))
vowels = "aeiou"
for v in vowels:
    print(v, data.lower().count(v))

6
使用 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

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}

我认为你可以使用 d = defaultdict(int) - user2555451

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)

你应该使用 "if letter.lower() in vowel" 来考虑大写元音字母。 - Nan
那不是最简单的方法。这个才是:count = len(re.findall('[aeiouAEIOU]', Sentence))。但问题要求每个字母都有一个独立的计数,所以两种解决方案都不正确。 - Mark Ransom

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 vowels from raw input。你会在那里找到几个不错的解决方案,可以轻松地应用于你的特定情况。我认为如果你详细阅读第一个答案,就能正确地重写你的代码。

4

使用列表推导式的另一种解决方案:

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

3
>>> string = "aswdrtio"
>>> [string.lower().count(x) for x in "aeiou"]
[1, 0, 1, 1, 0]

计算“字符串”中每个元音字母的出现次数,并将它们放入列表中,例如[1a, 0e, 1i, 1o, 0u]。lower()函数将“字符串”转换为小写,因此如果有大写元音字母,也会被计算在内。 - david clark

2
count = 0 

string = raw_input("Type a sentence and I will count the vowels!").lower()

for char in string:

    if char in 'aeiou':

        count += 1

print count

你可以使用 string.lower() 来遍历字符串,而不仅仅是迭代普通的输入字符串,因为似乎 OP 想要处理大写字母。此外,你判断元音的测试可以简单地写成 if char in "aeiou": - Efferalgan
很棒的建议。谢谢! - Benjamin Tunney

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