pyton 統計單詞並排序-ok

xychong123發表於2017-03-19

  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. c1=words_dict.items()
  26. c2=[]
  27. for i in c1:
  28.     c2.append((i[1],i[0]))
  29. d2={}
  30. d2={}
  31. for i in c2:
  32.     d2[i[0]]=i[1]
  33. def mySort(a):
  34.     lo = len(a) - 1
  35.     i = 0
  36.     while i < lo + 1:
  37.         j = lo
  38.         while j >= i:
  39.             if (a[j - 1] > a[j]):
  40.                 a[j], a[j - 1] = a[j - 1], a[j]
  41.             j = j - 1
  42.         i = i + 1
  43. if __name__ == '__main__':
  44.     for i in sorted(d2.keys()):
  45.         print d2[i], ':', i

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

相關文章