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内置函数delattr的具体用法

delattr 函数用于删除属性。 delattr(x, 'foobar') 相等于 del x.foobar。 语法 setattr 语法:delattr(object, nam...

HTML中使用python屏蔽一些基本功能的方法

进行数据解析的理由不计其数,相关的工具和技巧也同样如此。但是,当您需要用这些数据做一些新的事情时,即使有“合适的”工具可能也是不够的。这一担心对于异类数据源的集成同样存在。用来做这项工作...

Python 多进程和数据传递的理解

Python 多进程和数据传递的理解 python不仅线程用的是系统原生线程,进程也是用的原生进程 进程的用法和线程大同小异 import multiprocessing...

django和vue实现数据交互的方法

我使用的是jQuery的ajax与django进行数据交互,遇到的问题是django的csrf 传输数据的方法如下: $(function() { $.ajax({ ur...

python redis 删除key脚本的实例

单机模式 代码片段 安装 pip install redis import redis r = redis.Redis(host='192.168.1.3', port=6188,d...