python 統計文章單詞個數 -2

xychong123發表於2017-03-16

  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.     for i in str1:
  21.         if i not in words_dict:
  22.             words_dict[i] = 1
  23.         else:
  24.             words_dict[i] = words_dict[i] + 1

  25.     for k, v in words_dict.items():
  26.         print k, v

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

相關文章