在String Python中计算元音

时间:2013-11-14 00:05:08

标签: 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)

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

30 个答案:

答案 0 :(得分:15)

你想要的就是这么简单:

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

如果您不了解它们,请参考map*上有一个参考。

答案 1 :(得分: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

答案 2 :(得分:6)

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

答案 3 :(得分:6)

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

(记住间距s)

答案 4 :(得分: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

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}

答案 5 :(得分:4)

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。你会在那里找到一些很好的解决方案,可以很容易地为你的特定情况采用。我想如果你仔细阅读第一个答案,你将能够以正确的方式重写你的代码。

答案 6 :(得分: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

答案 7 :(得分:1)

对于那些寻找最简单解决方案的人来说,这就是一个

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)

答案 8 :(得分:1)

具有列表理解功能的另一种解决方案:

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

答案 9 :(得分:1)

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

答案 10 :(得分:1)

我写了一个用于计算元音的代码。您可以使用它来计算您选择的任何角色。我希望这有帮助! (用Python 3.6.0编码)

while(True):
phrase = input('Enter phrase you wish to count vowels: ')
if phrase == 'end': #This will to be used to end the loop 
    quit() #You may use break command if you don't wish to quit
lower = str.lower(phrase) #Will make string lower case
convert = list(lower) #Convert sting into a list
a = convert.count('a') #This will count letter for the letter a
e = convert.count('e')
i = convert.count('i')
o = convert.count('o')
u = convert.count('u')

vowel = a + e + i + o + u #Used to find total sum of vowels

print ('Total vowels = ', vowel)
print ('a = ', a)
print ('e = ', e)
print ('i = ', i)
print ('o = ', o)
print ('u = ', u)

答案 11 :(得分:1)

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

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

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

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

答案 12 :(得分:0)

sentence = input("Enter a sentence: ").upper()
#create two lists
vowels = ['A','E',"I", "O", "U"]
num = [0,0,0,0,0]

#loop through every char
for i in range(len(sentence)):
#for every char, loop through vowels
  for v in range(len(vowels)):
    #if char matches vowels, increase num
      if sentence[i] == vowels[v]:
        num[v] += 1

for i in range(len(vowels)):
  print(vowels[i],":", num[i])

答案 13 :(得分:0)

def vowel_count(string):
    
    string = string.lower()
    count = 0
    vowel_found = False 
    
    for char in string:
        if char in 'aeiou': #checking if char is a vowel
            count += 1
            vowel_found = True
            
    if vowel_found == False:
        print(f"There are no vowels in the string: {string}")
            
    return count

string = "helloworld"

result = vowel_count(string) #calling function

print("No of vowels are: ", result)

答案 14 :(得分:0)

这是一个简单的不觉得复杂的python中查找三元for循环你会得到它。

print(sum([1 for ele in input() if ele in "aeiouAEIOU"]))

答案 15 :(得分:0)

from collections import Counter

count = Counter()
inputString = str(input("Please type a sentence: "))

for i in inputString:
    if i in "aeiouAEIOU":
          count.update(i)          
print(count)

答案 16 :(得分:0)

您可以使用regex和dict理解:

import re
s = "aeiouuaaieeeeeeee"

regex函数findall()返回包含所有匹配项的列表

这里x是键,而正则表达式返回的列表长度是该字符串中每个元音的计数,请注意,正则表达式将找到您引入“ aeiou”字符串中的任何字符。

foo = {x: len(re.findall(f"{x}", s)) for x in "aeiou"}
print(foo)

返回:

{'a': 3, 'e': 9, 'i': 2, 'o': 1, 'u': 2}

答案 17 :(得分:0)

def vowels():
    numOfVowels=0
    user=input("enter the sentence: ")
    for vowel in user:
        if vowel in "aeiouAEIOU":
            numOfVowels=numOfVowels+1
    return numOfVowels
print("The number of vowels are: "+str(vowels()))

答案 18 :(得分:0)

...

vowels = "aioue"
text = input("Please enter your text: ")
count = 0

for i in text:
    if i in vowels:
        count += 1

print("There are", count, "vowels in your text")

...

答案 19 :(得分:0)

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

def checkForVowels(some_string):
  #will save all counted vowel variables as key/value
  amountOfVowels = {}
  for i in vowels:
    # check for lower vowel variables
    if i in some_string:
      amountOfVowels[i] = some_string.count(i)
    #check for upper vowel variables
    elif i.upper() in some_string:
      amountOfVowels[i.upper()] = some_string.count(i.upper())
  return amountOfVowels

print(checkForVowels("sOmE string"))

您可以在此处测试此代码:https://repl.it/repls/BlueSlateblueDecagons

因此,希望玩得开心一点。

答案 20 :(得分:0)

from collections import defaultdict


def count_vowels(word):
    vowels = 'aeiouAEIOU'
    count = defaultdict(int)   # init counter
    for char in word:
        if char in vowels:
            count[char] += 1
    return count

一种计算单词中元音的Python方法,与javac++中不同,实际上不需要预处理单词字符串,不需要str.strip()或{{1} }。但是,如果您想不区分大小写地计算元音,那么在进入for循环之前,请使用str.lower()

答案 21 :(得分:0)

假设

S =“组合”

import re
print re.findall('a|e|i|o|u', S)

打印: ['o','i','a','i','o']

  

针对您的情况(案例1):

txt =“等等等等...”

import re
txt = re.sub('[\r\t\n\d\,\.\!\?\\\/\(\)\[\]\{\}]+', " ", txt)
txt = re.sub('\s{2,}', " ", txt)
txt = txt.strip()
words = txt.split(' ')

for w in words:
    print w, len(re.findall('a|e|i|o|u', w))
  

案例2

import re,  from nltk.tokenize import word_tokenize

for w in work_tokenize(txt):
        print w, len(re.findall('a|e|i|o|u', w))

答案 22 :(得分:0)

Simplest Answer:

inputString = str(input("Please type a sentence: "))

vowel_count = 0

inputString =inputString.lower()

vowel_count+=inputString.count("a")
vowel_count+=inputString.count("e")
vowel_count+=inputString.count("i")
vowel_count+=inputString.count("o")
vowel_count+=inputString.count("u")

print(vowel_count)

答案 23 :(得分:0)

这对我有用,也可以计算辅音(但是如果你真的不想要辅音计数,那么你需要做的就是删除最后一个for循环和最后一个变量at顶部。

她是python代码:

data = input('Please give me a string: ')
data = data.lower()
vowels = ['a','e','i','o','u']
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowelCount = 0
consonantCount = 0


for string in data:
    for i in vowels:
        if string == i:
            vowelCount += 1
    for i in consonants:
        if string == i:
            consonantCount += 1

print('Your string contains %s vowels and %s consonants.' %(vowelCount, consonantCount))

答案 24 :(得分:0)

string1 ='我爱我的印度' 元音= 'AEIOU' 我在元音:   print i +“ - >”+ str(string1.count(i))

答案 25 :(得分:0)

count = 0
s = "azcbobobEgghakl"
s = s.lower()
for i in range(0, len(s)):
    if s[i] == 'a'or s[i] == 'e'or s[i] == 'i'or s[i] == 'o'or s[i] == 'u':
        count += 1
print("Number of vowels: "+str(count))

答案 26 :(得分:-1)

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

答案 27 :(得分:-1)

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

答案 28 :(得分:-1)

  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 

答案 29 :(得分:-1)

def check_vowel(char):
    chars = char.lower()
    list = []
    list2 = []
    for i in range(0, len(chars)):
        if(chars[i]!=' '):
            if(chars[i]=='a' or chars[i]=='e' or chars[i]=='i' or chars[i]=='o' or chars[i]=='u'):
                list.append(chars[i])
            else:
                list2.append(chars[i])
    return list, list2
    

char = input("Enter your string:")
list,list2 = check_vowel(char)
if len(list)==1:
    print("Vowel is:", len(list), list)
if len(list)>1:
    print("Vowels are:", len(list), list)
if len(list2)==1:
    print("Constant is:", len(list2), list2)
if len(list2)>1:
    print("Constants are:", len(list2), list2)