计算元音的 Python 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24361761/
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 04:28:56  来源:igfitidea点击:

Python code to count vowels

pythonloops

提问by user3766695

Assume sis a string of lower case characters.

假设s是一串小写字符。

Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:

编写一个程序来计算字符串中包含的元音数量s。有效的元音是:'a''e''i''o',和'u'。例如,如果s = 'azcbobobegghakl',您的程序应该打印:

Number of vowels: 5

元音数: 5

I have this so far

到目前为止我有这个

count = 0
vowels = 'a' or 'e' or 'i' or 'o' or 'u'
    for vowels in s:
        count +=1
print ('Number of vowels: ' + count)

Can anyone tell me what is wrong with it?

谁能告诉我它有什么问题?

回答by Fredrik Pihl

As a start, try this:

首先,试试这个:

In [9]: V = ['a','e','i','o','u']

In [10]: s = 'azcbobobegghakl'

In [11]: sum([1 for i in s if i in V])
Out[11]: 5

回答by Padraic Cunningham

Using your own loop.

使用您自己的循环。

count = 0
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
    if char in vowels: # check if each char in your string is in your list of vowels
        count += 1
print ('Number of vowels: ' + str(count)) # count is an integer so you need to cast it as a str

You can use string formatting also:

您也可以使用字符串格式:

print ('Number of vowels: {} '.format(count))

回答by jonrsharpe

A couple of problems. First, your assignment to vowelsdoesn't do what you think it does:

几个问题。首先,您的分配vowels没有做您认为的那样:

>>> vowels = 'a' or 'e' or 'i' or 'o' or 'u'
>>> vowels
'a'

Python evaluates orlazily; as soon as any of the predicates evaluates Trueit is returned. Non-empty sequences, including strings other than ""evaluate True, so 'a'is returned straight away.

Pythonor惰性求值;一旦任何谓词求值,True它就会被返回。非空序列,包括除""评估之外的字符串True,因此'a'会立即返回。

Second, when you iterate over s, you ignore that assignment anyway:

其次,当您迭代 时s,您无论如何都会忽略该分配:

>>> for vowels in "foo":
    print(vowels)


f
o
o

for x in y:assigns each item in the iterable yto the name xin turn, so anything previously assigned to xis not longer accessible via that name.

for x in y:依次将 iterabley中的每个项目分配给名称x,因此以前分配给的任何内容x都不能再通过该名称访问。

I think what you want is:

我想你想要的是:

count = 0
vowels = set("aeiou")
for letter in s:
    if letter in vowels:
        count += 1

回答by sundar nataraj

A different implementation using counter

使用计数器的不同实现

from collections import Counter
s='azcbobobegghakl'
vowels="aeiou"
c=Counter(s)
print sum([c[i] for i in set(vowels).intersection(c.keys())])

the statement set(vowels).intersection(c.keys())this returns the dictint vowels present in the sentence

声明set(vowels).intersection(c.keys())这将返回dictint元音出现在句子

回答by Aashish P

This is also another solution,

这也是另一种解决方案,

In [12]: vowels = ['a', 'e', 'i', 'o', 'u']

In [13]: str = "azcbobobegghakl"

In [14]: sum([str.count(elem) for elem in vowels])
Out[14]: 5

Using string.count()

使用 string.count()

回答by Rahul Khatri

here is the simple one:

这是一个简单的:

count = 0    #initialize the count variable

def count_vowel(word):    #define a function for counting the vowels
    vowels = 'aeiouAEIOU'    #A string containing all the vowels
    for i in range(word):    #traverse the string
        if i in vowels:    #check if the the character is contained in the vowel string
            count = count + 1    #update the count
return count

回答by xxyzzy

Here is a sample that uses Counter and is more compact and even a little faster than Sundar's for larger strings:

这是一个使用 Counter 的示例,对于较大的字符串,它比 Sundar 的更紧凑,甚至更快一点:

from collections import Counter 
cnt = Counter('this and that')
sum([cnt[x] for x in 'aeiou'])

Here is a time test to compare 3 approaches:

这是比较 3 种方法的时间测试:

import time
from collections import Counter 
s = 'That that is is is not that that is not is not.  This is the understanding of all who begin to think.'
c = Counter(s)
dt1 = dt2 = dt3 = dt4 = 0; 
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for i in range(100000):
    ms0 = time.time()*1000.0
    s1 = sum([c[x] for x in 'aeiou'])
    ms1 = time.time()*1000.0
    dt1 += ms1 - ms0
for i in range(100000):
    ms1 = time.time()*1000.0
    s2 = sum([c[x] for x in set(vowels).intersection(c.keys())])
    ms2 = time.time()*1000.0
    dt2 += ms2 - ms1
for i in range(100000):
    ms2 = time.time()*1000.0
    s3 = 0
    for char in s:
        if char in vowels: # check if each char in your string is in your list of vowels
            s3 += 1
    ms3 = time.time()*1000.0
    dt3 += ms3 - ms2
print('sums:', s1, s2, s3)
print('times:', dt1, dt2, dt3)
print('relative:  {:.0%}{:.0%}{:.0%}'.format(dt1/dt2, dt2/dt2, dt3/dt2))

Results (average of six runs), versions: this, Sundar, simple sums: 26 26 26 times: 392 494 2626
relative: 80% 100% 532%

结果(六次运行的平均值),版本:this,Sundar,简单和:26 26 26 次:392 494 2626
相对:80% 100% 532%

回答by iLabQC

x = len(s)        
a = 0        
c = 0        
while (a < x):        
    if s[a] == 'a' or s[a] == 'e' or s[a] == 'i' or s[a] == 'o' or s[a] == 'u':        
        c += 1        
    a = a+1        
print "Number of vowels: " + str(c)

The above code is for beginners

以上代码适合初学者

回答by Luke D

My solution:

我的解决方案:

s = 'aassfgia'
vowels = 0
for x in s:
    if x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u':
        vowels += 1
        print x
print vowels

回答by vatsal

For counting vowels from string

用于计算字符串中的元音

s = "Some string here" 

or

或者

s = intput(raw_input("Enter ur string"))

s1 = s.lower()
count = 0
vowels = set("aeiou")
for letter in s1:
  if letter in vowels:
    count += 1
print 'Number of vowels:' ,count

this will give u output for total count of vowels in given string

这将为您提供给定字符串中元音总数的输出