2014-07-26 55 views
0

我一直在试图产生一个程序的输出:Python的初学者问题 - 字典

Enter line: which witch 
Enter line: is which 
Enter line: 
is 1 
which 2 
witch 1 

我它是如何想的工作是让你输入几行,并没有被提交时它会统计每一行的数量。

目前,我无法计算句子中的单个行,但只能计算整个句子。我的代码:

dic = {} 

while True: 
    line = input('Enter Line: ') 
    line = line.lower()  
    if not line: 
     break 

    dic.setdefault(line, 0) 
    dic[line] += 1 
for line, n in sorted(dic.items()): 
    print(line, n) 

将会产生输出:

Enter line: which witch 
Enter line: is which 
Enter line: 
which witch 1 
is which 1 

,而不是第一个

任何帮助,将不胜感激。谢谢

回答

2

该代码是使用每一行作为字典键,而不是字。使用str.split分割线并迭代单词。

dic = {} 

while True: 
    line = input('Enter Line: ') 
    line = line.lower()  
    if not line: 
     break 
    for word in line.split(): # <----- 
     dic.setdefault(word, 0) # <----- 
     dic[word] += 1   # <----- 
for line, n in sorted(dic.items()): 
    print(line, n) 

顺便说一句,可以考虑使用collections.Counter这类任务(计数事件)的。

+1

...或者使用'dic [word] = dic.get(word,0)+ 1'而不是'setdefault'这两行代码(它自己调用'get()'并返回一个值'不使用)。 –

+0

谢谢。我一直在这上面花钱! – user3879060