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

yipeiwu_com5年前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处理excel绘制雷达图

本文实例为大家分享了python处理excel绘制雷达图的具体代码,供大家参考,具体内容如下 python处理excel制成雷达图,利用工具plotly在线生成,事先要安装好xlrd组件...

Python编程实现二分法和牛顿迭代法求平方根代码

Python编程实现二分法和牛顿迭代法求平方根代码

求一个数的平方根函数sqrt(int num) ,在大多数语言中都提供实现。那么要求一个数的平方根,是怎么实现的呢? 实际上求平方根的算法方法主要有两种:二分法(binary searc...

Python中的迭代器与生成器高级用法解析

迭代器 迭代器是依附于迭代协议的对象——基本意味它有一个next方法(method),当调用时,返回序列中的下一个项目。当无项目可返回时,引发(raise)StopIteration异常...

Eclipse和PyDev搭建完美Python开发环境教程(Windows篇)

Eclipse和PyDev搭建完美Python开发环境教程(Windows篇)

本文讲诉如何搭建Python开发环境,具体如下: 目录 安装Python python for eclipse插件安装 配置PyDev插件 测试 安装Python...

python数字图像处理之高级形态学处理

python数字图像处理之高级形态学处理

形态学处理,除了最基本的膨胀、腐蚀、开/闭运算、黑/白帽处理外,还有一些更高级的运用,如凸包,连通区域标记,删除小块区域等。 1、凸包 凸包是指一个凸多边形,这个凸多边形将图片中所有的白...