[Python] python统计文本文件内单词数量 →→→→→进入此内容的聊天室

来自 , 2019-06-30, 写在 Python, 查看 113 次.
URL http://www.code666.cn/view/1a336426
  1. # count lines, sentences, and words of a text file
  2. # set all the counters to zero
  3. lines, blanklines, sentences, words = 0, 0, 0, 0
  4. print '-' * 50
  5. try:
  6.   # use a text file you have, or google for this one ...
  7.   filename = 'GettysburgAddress.txt'
  8.   textf = open(filename, 'r')
  9. except IOError:
  10.   print 'Cannot open file %s for reading' % filename
  11.   import sys
  12.   sys.exit(0)
  13. # reads one line at a time
  14. for line in textf:
  15.   print line,   # test
  16.   lines += 1
  17.  
  18.   if line.startswith('\n'):
  19.     blanklines += 1
  20.   else:
  21.     # assume that each sentence ends with . or ! or ?
  22.     # so simply count these characters
  23.     sentences += line.count('.') + line.count('!') + line.count('?')
  24.    
  25.     # create a list of words
  26.     # use None to split at any whitespace regardless of length
  27.     # so for instance double space counts as one space
  28.     tempwords = line.split(None)
  29.     print tempwords  # test
  30.    
  31.     # word total count
  32.     words += len(tempwords)
  33.    
  34. textf.close()
  35. print '-' * 50
  36. print "Lines      : ", lines
  37. print "Blank lines: ", blanklines
  38. print "Sentences  : ", sentences
  39. print "Words      : ", words
  40. # optional console wait for keypress
  41. from msvcrt import getch
  42. getch()
  43. #//python/5738

回复 "python统计文本文件内单词数量"

这儿你可以回复上面这条便签

captcha