在字符串 Python 中计算元音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19967001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:06:56  来源:igfitidea点击:

Count Vowels in String Python

python

提问by user2975192

I'm trying to count how many occurrences there are of specific characters in a string, but the output is wrong.

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

Here is my code:

这是我的代码:

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)

If I enter the letter Athe output would be: 1 1 1 1 1

如果我输入这封信A,输出将是:1 1 1 1 1

回答by user2975192

What you want can be done quite simply like so:

您可以像这样简单地完成您想要的操作:

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

In case you don't know them, here is a reference on mapand one on the *.

如果您不认识它们,这里有一个关于 的参考map和一个关于*.

回答by Prashant Kumar

Use a Counter

用一个 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

Counteris only available in Python 2.7+. A solution that should work on Python 2.5 would utilize defaultdict

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}

回答by sashkello

if A or a in strimeans if A or (a in stri)which is if True or (a in stri)which is always True, and same for each of your ifstatements.

if A or a in stri意味着if A or (a in stri)which is if True or (a in stri)which always True,并且对于您的每个if语句都是相同的。

What you wanted to say is if A in stri or a in stri.

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

This is your mistake. Not the only one - you are not really counting vowels, since you only check if string contains them once.

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

The other issue is that your code is far from being the best way of doing it, please see, for example, this: Count vowels from raw input. You'll find a few nice solutions there, which can easily be adopted for your particular case. I think if you go in detail through the first answer, you'll be able to rewrite your code in a correct way.

另一个问题是,您的代码远不是最好的方法,例如,请参阅:从原始输入计算元音。您会在那里找到一些不错的解决方案,这些解决方案可以很容易地用于您的特定情况。我认为如果您详细了解第一个答案,您将能够以正确的方式重写您的代码。

回答by inspectorG4dget

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

回答by kyle k

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

回答by hanish

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

(remember the spacing s)

(记住间距 s)

回答by avina k

def count_vowel():
    cnt = 0
    s = 'abcdiasdeokiomnguu'
    s_len = len(s)
    s_len = s_len - 1
    while s_len >= 0:
        if s[s_len] in ('aeiou'):
            cnt += 1
        s_len -= 1
    print 'numofVowels: ' + str(cnt)
    return cnt

def main():
    print(count_vowel())

main()

回答by Simanto Bagchi

count = 0
name=raw_input("Enter your name:")
for letter in name:
    if(letter in ['A','E','I','O','U','a','e','i','o','u']):
       count=count + 1
print "You have", count, "vowels in your name."

回答by timgeb

For brevity and readability, use a dictionary comprehension.

为了简洁和可读性,请使用字典理解。

>>> inp = raw_input() # use input in Python3
hI therE stAckOverflow!
>>> search = inp.lower()
>>> {v:search.count(v) for v in 'aeiou'}
{'a': 1, 'i': 1, 'e': 3, 'u': 0, 'o': 2}

Alternatively, you can consider a named tuple.

或者,您可以考虑命名元组。

>>> from collections import namedtuple
>>> vocals = 'aeiou'
>>> s = 'hI therE stAckOverflow!'.lower()
>>> namedtuple('Vowels', ' '.join(vocals))(*(s.count(v) for v in vocals))
Vowels(a=1, e=3, i=1, o=2, u=0)

回答by user6143812

  1 #!/usr/bin/python
  2 
  3 a = raw_input('Enter the statement: ')
  4 
  5 ########### To count number of words in the statement ##########
  6 
  7 words = len(a.split(' '))
  8 print 'Number of words in the statement are: %r' %words 
  9 
 10 ########### To count vowels in the statement ##########
 11 
 12 print '\n' "Below is the vowel's count in the statement" '\n'
 13 vowels = 'aeiou'
 14 
 15 for key in vowels:
 16     print  key, '=', a.lower().count(key)
 17