第 0004 题

2017-06-26  本文已影响0人  司徒道

任一个英文的纯文本文件,统计其中的单词出现的个数
这里的文本文件就用python之禅吧。

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

stop_symbol = ['.', ',', '*', '-', '!', '\n']
word_dict = {}
with open(r'./zen_of_python.txt', 'r') as f:
    for line in f:
        for s in stop_symbol:
            if s in line:
                line = line.replace(s, '')
        words = line.split(' ')
        for w in words:
            if w != '':
                word_dict[w] = word_dict.setdefault(w, 0) + 1

word_count = sorted(word_dict, key=word_dict.get, reverse=True)[:10]
for c in word_count:
    print(c, ': ', word_dict[c])

is : 10
than : 8
better : 8
to : 5
the : 5
idea : 3
one : 3
Although : 3
of : 3
never : 3

上一篇下一篇

猜你喜欢

热点阅读