计算 Python 字符串中的元音数量

2025-02-20 09:22:00
admin
原创
26
摘要:问题描述:我试图计算字符串中特定字符出现的次数,但输出是错误的。这是我的代码:inputString = str(input("Please type a sentence: ")) a = "a" A = "A" e = "e"...

问题描述:

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

这是我的代码:

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


解决方案 1:

你想要的事情可以很简单地完成,如下所示:

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

如果你不了解它们,这里有一个关于的参考资料map,还有一个关于的*

解决方案 2:

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

(记住间距 s)

解决方案 3:

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

解决方案 4:

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

解决方案 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}

解决方案 6:

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

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

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

解决方案 7:

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

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:

另一个使用列表理解的解决方案:

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:

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

解决方案 10:

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

解决方案 11:

我写了一个用于计数元音的代码。你可以用它来计算你选择的任何字符。希望这对你有帮助!(使用 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)

解决方案 12:

认为,

S =“组合”

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

打印:[‘o’, ‘i’, ‘a’, ‘i’, ‘o’]

用一句话概括你的案例(案例 1):

txt =“啦啦啦……”

import re
txt = re.sub('[
    
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))

解决方案 13:

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)

解决方案 14:

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

解决方案 15:

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

解决方案 16:

这对我来说很有效,并且也计算了辅音(认为这是一个奖励)但是,如果你真的不想要辅音计数,你所要做的就是删除最后一个 for 循环和顶部的最后一个变量。

以下是 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))

解决方案 17:

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)

解决方案 18:

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 方式,不像 injavac++,实际上不需要预处理单词字符串,不需要 forstr.strip()str.lower()。但如果您想不区分大小写地计算元音,那么在进入 for 循环之前,请使用str.lower()

解决方案 19:

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:

...

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

...

解决方案 21:

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

解决方案 22:

您可以使用正则表达式和字典理解:

import re
s = "aeiouuaaieeeeeeee"

正则表达式函数 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}

解决方案 23:

string1='I love my India'

vowel='aeiou'

for i in vowel:
  print i + "->" + str(string1.count(i))

解决方案 24:

这是一个简单的,不要觉得它复杂,在 python 中搜索三元 for 循环你就会得到它。

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

解决方案 25:

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)

解决方案 26:

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

解决方案 27:

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

解决方案 28:

  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 '
' "Below is the vowel's count in the statement" '
'
 13 vowels = 'aeiou'
 14 
 15 for key in vowels:
 16     print  key, '=', a.lower().count(key)
 17 

解决方案 29:

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)
相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1325  
  IPD(Integrated Product Development)流程作为一种先进的产品开发管理模式,在众多企业中得到了广泛应用。它涵盖了从产品概念产生到产品退市的整个生命周期,通过整合跨部门团队、优化流程等方式,显著提升产品开发的效率和质量,进而为项目的成功奠定坚实基础。深入探究IPD流程的五个阶段与项目成功之间...
IPD流程分为几个阶段   4  
  华为作为全球知名的科技企业,其成功背后的管理体系备受关注。IPD(集成产品开发)流程作为华为核心的产品开发管理模式,其中的创新管理与实践更是蕴含着丰富的经验和深刻的智慧,对众多企业具有重要的借鉴意义。IPD流程的核心架构IPD流程旨在打破部门墙,实现跨部门的高效协作,将产品开发视为一个整体的流程。它涵盖了从市场需求分析...
华为IPD是什么   3  
  IPD(Integrated Product Development)研发管理体系作为一种先进的产品开发模式,在众多企业的发展历程中发挥了至关重要的作用。它不仅仅是一套流程,更是一种理念,一种能够全方位提升企业竞争力,推动企业持续发展的有效工具。深入探究IPD研发管理体系如何助力企业持续发展,对于众多渴望在市场中立足并...
IPD管理流程   3  
  IPD(Integrated Product Development)流程管理旨在通过整合产品开发流程、团队和资源,实现产品的快速、高质量交付。在这一过程中,有效降低成本是企业提升竞争力的关键。通过优化IPD流程管理中的各个环节,可以在不牺牲产品质量和性能的前提下,实现成本的显著降低,为企业创造更大的价值。优化产品规划...
IPD流程分为几个阶段   4  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用