繁体   English   中英

Python计数元音

[英]Python Counting Vowels

我已经开始开发一个计算元音的程序,但是似乎一无所获。 我需要从字符串中算出元音,然后显示元音。 我需要通过将出现的次数存储在变量中来做到这一点。 像这样 :

    a = 0
    b = 0
    ....

    then print the lowest.

当前代码(不是那么多):

string = str(input("please input a string:  "))
edit= ''.join(string)


print(edit)

我只是靠自己尝试了多种方法,似乎一无所获。

>>> a="hello how are you"
>>> vowel_count = dict.fromkeys('aeiou',0)
>>> vowel_count 
{'a': 0, 'i': 0, 'e': 0, 'u': 0, 'o': 0}
>>> for x in 'aeiou':
...     vowel_count[x]=a.count(x)
... 
>>> vowel_count 
{'a': 1, 'i': 0, 'e': 2, 'u': 1, 'o': 3}

现在从这里您可以打印低和最大

您可以使用字典理解:

>>> example = 'this is an example string'
>>> vowel_counts = {c: example.count(c) for c in 'aeoiu'}
>>> vowel_counts
{'i': 2, 'o': 0, 'e': 5, 'u': 0, 'a': 2}

然后找到最小值,最大值等是微不足道的。

您可以使用字典解决此问题。 遍历每个字符,如果该字符是元音 ,则将其放入具有0计数的字典中 ,并将其计数增加1 ,对于每次出现的情况,请继续增加计数。

>>> string = str(input("please input a string:  "))
please input a string:  'Hello how are you'
>>> dt={}   # initialize dictionary
>>> for i in string:  # iterate over each character
...    if i in ['a','e','i','o','u']:   # if vowel
...       dt.setdefault(i,0)  # at first occurrence set count to 0
...       dt[i]+=1   # increment count by 1
...
>>> dt
{'a': 1, 'u': 1, 'e': 2, 'o': 3}
word = input('Enter Your word : ')
vowel = 'aeiou'
vowel_counter = {}

for char in word:
  if char in vowel:
    vowel_counter[char] = vowel_counter.setdefault(char,0)+1

sorted_result = sorted(vowel_counter.items(), reverse=True,key=lambda x : x[1])

for key,val in sorted_result:
  print(key,val)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM