2012-04-23 66 views
1
import re 
sums = dict() 
fh= open('wordcount.txt','r') 
for line in fh: 
    words = [word.lower() for word in re.findall(r'\b\w+\b', line)] 
    for word in (words): 
     if word in sums: 
      sums[word] += 1 
     else: 
      sums[word] = 1 
print sums 
fh.close 

结果表明Python:如何在单独的行中打印字典?

{'and': 1, 'heart': 1, 'love': 2, 'is': 1, 'pass': 1, 'rest': 1, 'wounded': 1, 'at': 3, 
'in': 3, 'lie': 1, 'winchelsea': 1, 'there': 1, 'easy': 1, 'you': 2, 'body': 1, 'be': 
1, 'rise': 1, 'shall': 4, 'may': 2, 'sussex': 1, 'montparnasse': 1, 'not': 3, 'knee': 
1, 'bury': 3, 'tongue': 1, 'champmedy': 1, 'i': 5, 'quiet': 1, 'air': 2, 'fresh': 1, 
'the': 1, 'grass': 1, 'my': 3} 

代码打印所有的字和计数频率字使用。

我想单独打印字典。

'and': 1 
'heart': 1 
'love': 2 
... 

任何可能的方式来做到这一点?

回答

15
>>> from pprint import pprint 
>>> pprint(sums) 
{'air': 2, 
'and': 1, 
'at': 3, 
'be': 1, 
'body': 1, 
....., # and so on... 
'you': 2} 
+0

谢谢你的另一种复杂的方式。按预期工作:) – ThanaDaray 2012-04-23 11:38:21

+0

不客气:D – jamylak 2012-04-23 11:39:07

+1

+1,我记得看到这个问IRL,看到有人告诉该人要求将其转换为JSON并打印出来,这导致了身体上的痛苦。 – 2012-04-23 11:39:08

2

您可以使用iteritems遍历键和值,从而能够根据需要格式化输出。假设字符串作为键和整数作为值:

for k, v in d.iteritems(): 
    print '%s: %d' % (k, v) 
1
>>>for x in sums: 
    print(repr(x),":",dic[x]) 


'and' : 1 
'heart' : 1 
'sussex' : 1 
'rise' : 1 
'love' : 2 
'be' : 1 
'may' : 2 
'the' : 1 
'is' : 1 
'in' : 3 
'body' : 1 
'rest' : 1 
'at' : 3 
'pass' : 1 
'not' : 3 
'knee' : 1 
'air' : 2 
'bury' : 3 
'tongue' : 1 
'lie' : 1 
'winchelsea' : 1 
'i' : 5 
'there' : 1 
'grass' : 1 
'quiet' : 1 
'shall' : 4 
'montparnasse' : 1 
'fresh' : 1 
'easy' : 1 
'wounded' : 1 
'you' : 2 
'champmedy' : 1 
'my' : 3 
0

使用lambda

f = lambda *x: null; 
f(*(print(x,":",y) for x,y in mydict.iteritems())) 

输出

key2 : 2 
key1 : 1