我已开始计算元音的程序,似乎无处可去。我需要从字符串中计算元音然后显示元音。我需要通过在变量中存储出现次数来做到这一点。像这样:
a = 0
b = 0
....
then print the lowest.
当前代码(不是那么多):
string = str(input("please input a string: "))
edit= ''.join(string)
print(edit)
我只是靠自己尝试了很多方法而且似乎无处可去。
答案 0 :(得分: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}
现在从这里你可以打印低和最大
答案 1 :(得分:2)
你可以使用词典理解:
>>> 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 :(得分:0)
您可以使用字典解决此问题。对每个字符进行迭代,如果字符是元音,则将其放入带有计数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}
答案 3 :(得分:0)
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)