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自定义异常实例详解

python自定义异常实例详解          本文通过两种方法对Python 自定义异常进行讲解,第一...

Python实现元素等待代码实例

这篇文章主要介绍了python实现元素等待代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一、为什么要元素等待? 在UI自动化...

Python使用add_subplot与subplot画子图操作示例

Python使用add_subplot与subplot画子图操作示例

本文实例讲述了Python使用add_subplot与subplot画子图操作。分享给大家供大家参考,具体如下: 子图:就是在一张figure里面生成多张子图。 Matplotlib对象...

Python利用pyHook实现监听用户鼠标与键盘事件

本文以一段简单的监听鼠标、键盘事件的程序,实现获取用户的输入(比如登录某些网站的账号、密码)的功能。经测试,对于一台“裸奔”的电脑,完全能获取到用户输入的任何信息;但是如果安装了杀毒软件...

python 将对象设置为可迭代的两种实现方法

1、实现 __getitem__(self) class Library(object): def __init__(self): self.value=['a','b'...