【问题标题】:Python Counting VowelsPython 数元音
【发布时间】:2015-01-05 23:47:41
【问题描述】:
我已经开始了一个计算元音的程序,但似乎无济于事。我需要从字符串中计算元音,然后显示元音。我需要通过将出现次数存储在变量中来做到这一点。像这样:
a = 0
b = 0
....
then print the lowest.
当前代码(没那么多):
string = str(input("please input a string: "))
edit= ''.join(string)
print(edit)
我自己尝试了很多方法,似乎都没有成功。
【问题讨论】:
标签:
python
python-3.x
counting
【解决方案1】:
您可以使用字典理解:
>>> 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}
然后找到最小值、最大值等是微不足道的。
【解决方案2】:
>>> 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}
现在您可以从这里打印 low nd max
【解决方案3】:
您可以使用字典来解决这个问题。遍历每个字符,如果该字符是元音,则将其放入 dictionary 中,计数为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}
【解决方案4】:
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)