利用Python列出最频繁的单词和它们的出现次数

读入文本文件《爱丽斯漫游仙境》英文版,可以从http://www.umich.edu/~umfandsf/other/ebooks/alice30.txt这个地址获取,列出其中使用最频繁的10个单词,并给出它们的出现次数

Python2.7上测试通过

import urllib2
import re
from collections import Counter
def get_data(url):
    resp = urllib2.urlopen(url).read().lower()
    return resp
def analyse(text, n=1):
    ''' show the n most common words in text '''
    res = Counter(re.split(r'\W+', text, flags=re.M)).most_common(n)
    print('words\ttimes')
    print('\n'.join([k+'\t'+str(v) for k,v in res]))
def main():
    data = get_data('http://www.umich.edu/~umfandsf/other/ebooks/alice30.txt')
    analyse(data, 10)
main()

结果是

words times

the 1642

and 872

to 729

a 632

it 595

she 553

i 543

of 514

said 462

you 411

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-10
学会珍惜,懂得珍惜。。人生只有经历才会懂得,只有懂得才知道珍惜。。珍惜生命中的所有能够相遇的人与经历,珍惜生命中遇到的每一份滋味与感受,看淡得失,善待自己。。
相似回答