2016-11-14 21 views
0
text = input("enter string:") 
text.lower() 
counta = text.count ("a") 
counte = text.count ("e") 
counti = text.count ("i") 
counto = text.count ("o") 
countu = text.count ("u") 

if counta > 0: 
print ("'a'",counta) 

if counte > 0: 
print ("'e'",counte) 

if counti> 0: 
print ("'i'",counti) 

if counto > 0: 
print ("'o'",counto) 

if countu > 0: 
print ("'u':",countu) 


leastFreq = [counta,counte,counti,counto,countu] 
leastFreq.sort() 
while 0 in leastFreq: leastFreq.remove(0) 
print (leastFreq) 

task =计数元音字,打印出现频率最低的元音。在这种情况下,“马铃薯”将打印:正确使用列表

'a' = 1 
'0' = 2 

我该如何让它只打印'a'?我可以使用min(leastFreq),但只会返回值“1”。我该怎么做才能使用格式'a'= 1打印,或者如果有多个元音具有相同的出现次数。

+1

与你的问题没有直接关系,但'text.lower()'本身并不做任何事情。你需要把它分配给某些东西。 – Kevin

+0

我假设这里的缩进错误是复制/粘贴到堆栈溢出的编辑器的结果? – mgilson

回答

0

你可以使用minadditional filter condition,测试元素是否为> 0

>>> leastFreq = [4, 2, 1, 0, 3, 0] 
>>> min(x for x in leastFreq if x > 0) 
1 

但这样一来,你失去了这个数是属于什么性质的信息。相反,你的五种不同的变量,你可以创建一个dictionary,映射元音各自罪状:

>>> text = "potato" 
>>> counts = {c: text.count(c) for c in "aeiou"} 
>>> counts 
{'a': 1, 'i': 0, 'e': 0, 'u': 0, 'o': 2} 
>>> counts["o"] 
2 

,然后再次进行min与发电机表达和特定key功能(由数进行排序,而不是元音本身)。

>>> min((c for c in counts if counts[c] > 0), key=counts.get) 
'a' 

如果你有兴趣在所有的字母数,你也可以使用collections.Counter

0

计数器和运营商的组合可能做的伎俩:

from collections import Counter 
import operator 
text = raw_input("enter string:") 
freq = Counter(i for i in text if i in 'aeiou') 
items = sorted(freq.items(),key=operator.itemgetter(1)) 
min = items[0][1] 
for character,frequency in items: 
    if frequency == min: 
     print character,frequency 
0

最低限度地改变你的代码:

leastFreq = [(counta, 'a'),(counte, 'e'),(counti, 'i'),(counto, 'o'),(countu, 'u')] 
leastvowel = min(leastFreq)[1] 

但是,你应该使用collections.Counter代替

from collections import Counter 
text = input("Enter text: ") 
c = Counter(character for character in text if character in 'aeiou') #get counts of vowels 
least_frequent = c.most_common()[-1] 

least_frequent会然后是一个元组,如('a', 1)

编辑:如果你希望所有最常见的物品,你可以使用itertools.groupby

lestfreq=list(next(itertools.groupby(c.most_common()[::-1], key=lambda x:x[1]))[1]) 

这看起来很复杂,但所有它说是采取有序列表,并采取所有元组具有相同第二价值并把它们放在一个列表中。

+1

整齐。如果两个元音具有相同(最小)频率,这将不会捕获。 –

+0

@PrateekDewan好点,看看我的编辑一个可能的解决方案 –