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 中判断列表是否为空的方法

在判断列表是否为空时,你更喜欢哪种方式?决定因素是什么? 在 Python 中有很多检查列表是否是空的方式,在讨论解决方案前,先说一下不同方法涉及到的不同因素。 我们可以把判断表达式可以...

解决Python字典写入文件出行首行有空格的问题

解决Python字典写入文件出行首行有空格的问题

模拟购物车程序,判断用户薪资是否是0 如果是0就需要输入薪资,并记录到文件内。 可以预先存个字典格式的字符串,然后去读取文件的时候读到的是字字符串然后再去用eval去转换成字典。 当我...

在Django中管理Users和Permissions以及Groups的方法

管理认证系统最简单的方法是通过管理界面。然而,当你需要绝对的控制权的时候,有一些低层 API 需要深入专研,我们将在下面的章节中讨论它们。 创建用户 使用 create_user 辅助函...

python数据预处理之将类别数据转换为数值的方法

在进行python数据分析的时候,首先要进行数据预处理。 有时候不得不处理一些非数值类别的数据,嗯, 今天要说的就是面对这些数据该如何处理。 目前了解到的大概有三种方法: 1,通过Lab...

Python实现的栈(Stack)

前言 Python本身已有顺序表(List、Tupple)的实现,所以这里从栈开始。 什么是栈 想象一摞被堆起来的书,这就是栈。这堆书的特点是,最后被堆进去的书,永远在最上面。从这堆书里...