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解决Fedora解压zip时中文乱码的方法

前言 很多时候在windows下压缩文件没问题,但是到了Linux下,出现乱码,很常见。以前在Ubuntu下,用`unzip -O GBK filename.zip` 就可以搞定。 换了...

python实现可变变量名方法详解

如果要写一个程序,让x1为1,x2为2,然后直到x100为100,你会怎么做? 在C这种静态语言里,变量名这个标识符实际上会被编译器直接翻译成内存地址,所以除了手动设置每个变量的值以外,...

基于Django统计博客文章阅读量

如何精确地记录一篇文章的阅读量是一个比较复杂的问题,不过对于我们的博客来说,没有必要记录的那么精确。因此我们使用一种简单但有效的方式来记录博客文章的阅读量:文章每被浏览一次,则其阅读量...

Pytorch实现GoogLeNet的方法

Pytorch实现GoogLeNet的方法

GoogLeNet也叫InceptionNet,在2014年被提出,如今已到V4版本。GoogleNet比VGGNet具有更深的网络结构,一共有22层,但是参数比AlexNet要少12倍...

理解python多线程(python多线程简明教程)

对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂。所以,这里力图用简单的例子,让你对多线程有个初步的认识。 单线程   在好些年前的MS-DOS时代,操作系...