python统计文本文件内单词数量的方法

yipeiwu_com6年前Python基础

本文实例讲述了python统计文本文件内单词数量的方法。分享给大家供大家参考。具体实现方法如下:

# count lines, sentences, and words of a text file
# set all the counters to zero
lines, blanklines, sentences, words = 0, 0, 0, 0
print '-' * 50
try:
 # use a text file you have, or google for this one ...
 filename = 'GettysburgAddress.txt'
 textf = open(filename, 'r')
except IOError:
 print 'Cannot open file %s for reading' % filename
 import sys
 sys.exit(0)
# reads one line at a time
for line in textf:
 print line,  # test
 lines += 1
 if line.startswith('\n'):
  blanklines += 1
 else:
  # assume that each sentence ends with . or ! or ?
  # so simply count these characters
  sentences += line.count('.') + line.count('!') + line.count('?')
  # create a list of words
  # use None to split at any whitespace regardless of length
  # so for instance double space counts as one space
  tempwords = line.split(None)
  print tempwords # test
  # word total count
  words += len(tempwords)
textf.close()
print '-' * 50
print "Lines   : ", lines
print "Blank lines: ", blanklines
print "Sentences : ", sentences
print "Words   : ", words
# optional console wait for keypress
from msvcrt import getch
getch()

希望本文所述对大家的python程序设计有所帮助。

相关文章

使用Python AIML搭建聊天机器人的方法示例

AIML全名为Artificial Intelligence Markup Language(人工智能标记语言),是一种创建自然语言软件代理的XML语言,是由RichardS. Wall...

Python中extend和append的区别讲解

append() 方法向列表的尾部添加一个新的元素。只接受一个参数。 >>> num = [1,2] >>> num.append(3) >...

python中使用print输出中文的方法

python中使用print输出中文的方法

看Python简明教程,学习使用print打印字符串,试了下打印中文,不行。 编辑环境:IDLE 上网搜了下解决办法,各种说法,试了两种: print u"学习" print (un...

Django+uni-app实现数据通信中的请求跨域的示例代码

Django+uni-app实现数据通信中的请求跨域的示例代码

前后端分离的模式下,后端使用Django RestFramework,前端使用uni-app来进行APP的开发。 前端代码: Django后端跨域配置 settings.py配...

初探利用Python进行图文识别(OCR)

初探利用Python进行图文识别(OCR)

话说什么是OCR????? 简介 OCR技术是光学字符识别的缩写(Optical Character Recognition),是通过扫描等光学输入方式将各种票据、报刊、书籍、文稿及其...