Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

python - How to print dict in separate line?

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

result shows

{'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}

The code print all the word and count frequency word use.

I would like to print dict in separate line.

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

Any possible way to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> from pprint import pprint
>>> pprint(sums)
{'air': 2,
 'and': 1,
 'at': 3,
 'be': 1,
 'body': 1,
 ....., # and so on...
 'you': 2}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...