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实现快速排序算法及去重的快速排序的简单示例

快速排序由于排序效率在同为O(N*logN)的几种排序方法中效率较高,因此经常被采用。 该方法的基本思想是: 1.先从数列中取出一个数作为基准数。 2.分区过程,将比这个数大的数全放到它...

python解析html提取数据,并生成word文档实例解析

简介 今天试着用ptyhon做了一个抓取网页内容,并生成word文档的功能,功能很简单,做一下记录以备以后用到。 生成word用到了第三方组件python-docx,所以先进行第三方组件...

python中使用正则表达式的后向搜索肯定模式(推荐)

正则表达式并不是Python的一部分。正则表达式是用于处理字符串的强大工具,拥有自己独特的语法以及一个独立的处理引擎,效率上可能不如str自带的方法,但功能十分强大。得益于这一点,在提供...

Python开发的十个小贴士和技巧及长常犯错误

下面是十个Python中很有用的贴士和技巧。其中一些是初学这门语言常常会犯的错误。 注意:假设我们都用的是Python 3 1. 列表推导式 你有一个list:bag = [1, 2,...

Python学习笔记之解析json的方法分析

Python学习笔记之解析json的方法分析

本文实例讲述了Python解析json的方法。分享给大家供大家参考,具体如下: 刚学习到Python中解析json的方法,觉得有必要在这里坐下笔记。 我是在python的内部环境中看的...