2016-11-15 68 views
0
text = 'hello' 
vowels = 'aeiou' 


for char in text.lower(): 
    if char in vowels: 




print(minimum_dict) 

我该怎么做才能让我编写的这个程序打印出“元音x出现的次数”。从字典中打印语句

我试过但我无法让它正常工作,程序是在哪里有一个词的输入,它检查发现最不频繁的元音。

回答

1

您可以遍历字典来获取密钥和值。 items返回一个元组对。

包括以下部分代码打印所需的结果:

for key,value in minimum_dict.items(): 
    print("Vowel ", key, "occurs", value ," times") 

minimum_dict.items()返回,因为他们key到字典项的列表和它相关的value:在这种情况下

value相当于minimum_dict[key]

+2

只有代码答案不是很有帮助。参考[答]并添加解释。也没有必要复制他的整个代码集,只有你已经改变的部分 – TemporalWolf

+0

@makavelllli我添加了一个编辑,但是在这种情况下,短版本是'value'相当于'minimum_dict [key]'。这就是'minimum_dict.items()'为你所做的。 – TemporalWolf

0
for vowel, occurrences in minimum_dict.items(): 
    print("vowel", vowel, "occurs ", occurrences, "times") 

通过您的最低限度地存在的元音的字典这将循环,并且对于每个元音/出现对将打印字符串“母音”,则实际元音,字符串“发生”,出现的次数,并字符串“times”。

print()函数接受任意数量的未命名参数并将它们转换为字符串,然后将它们写入输出。

1

您的代码可以使用collections.defaultdict()作为被简化:

from collections import Counter 
Counter(text) 

>>> from collections import defaultdict 
>>> text = 'hello' 
>>> vowels = 'aeiou' 
>>> vowel_count = defaultdict(int) 
>>> for c in text: 
...  if c in vowels: 
...   vowel_count[c] += 1 
... 
>>> vowel_count 
{'e': 1, 'o': 1} 

如果你有来存储所有的字符个数,这个代码可以进一步使用collections.Counter()为简化