python 統計單詞個數


根據一篇英文文章統計其中單詞出現最多的10個單詞。

# -*- coding: utf-8 -*-
import urllib2
import re
from collections import Counter

'''
007之雷霆谷 You Only Live Twice',可以從http://novel.tingroom.com/jingdian/1584/47084.html這個地址獲取,
列出其中使用最頻繁的10個單詞,並給出它們的出現次數
Python2.7上測試通過
'''

'''根據URL網址讀取數據'''
def Get_Data(url):
  data = urllib2.urlopen(url).read()
  return data

'''統計單詞及個數,text是要統計的文章字符串,n是統計次數最多的前幾個'''
def PrintWordsCount(text,n=1):
  '''調用Counter用正則進行拆分'''
  wordCountList = Counter(re.split(r'\W+', text, flags=re.M|re.I)).most_common(n)
  print '單詞\t次數'
  print '\n'.join([w+'\t'+str(c) for w,c in wordCountList])

#測試代碼
def test():
url ='http://novel.tingroom.com/jingdian/1584/47084.html'
data = Get_Data(url)
PrintWordsCount(data,10)
test()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM