python 統計文章單詞個數

xychong123發表於2017-03-16
檔案模版:
There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real!
Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.

執行結果:
C:\ProgramData\Anaconda2\python.exe C:/Users/xuyuch/PycharmProjects/untitled1/test1/word.py
Counter({'you': 7, 'to': 6, 'want': 5, 'and': 2, 'do': 2, 'them': 2, 'one': 2, 'go': 2, 'what': 2, 'be': 2, 'life': 2, 'dream': 2, '': 1, 'all': 1, 'because': 1, 'have': 1, 'just': 1, 'moments': 1, 'hug': 1, 'are': 1, 'in': 1, 'miss': 1, 'your': 1, 'from': 1, 'for': 1, 'things': 1, 'there': 1, 'when': 1, 'only': 1, 'much': 1, 'real': 1, 'someone': 1, 'that': 1, 'chance': 1, 'dreams': 1, 'where': 1, 'so': 1, 'pick': 1, 'the': 1})


Process finished with exit code 0



  1. lines_count = 0
  2. words_count = 0
  3. chars_count = 0
  4. words_dict = {}
  5. lines_list = []
  6. c1 = ['!', '?', ';', '.', ',']
  7. all_line = ''
  8. import collections
  9. with open('c:\invalid.txt', 'r') as f:
  10.     for line in f:
  11.         line = line.strip('\n')
  12.         lines_count = lines_count + 1
  13.         all_line=all_line+line.lower()
  14.        # print line
  15.     #print all_line
  16.     for i in c1:
  17.         all_line=all_line.replace(i,' ')
  18.     #print all_line
  19.     str1=all_line.split(' ')
  20.     cnt=collections.Counter(str1)
  21.     #print str1
  22.     print cnt

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/20747382/viewspace-2135470/,如需轉載,請註明出處,否則將追究法律責任。

相關文章