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程序设计有所帮助。

相关文章

3行Python代码实现图像照片抠图和换底色的方法

3行Python代码实现图像照片抠图和换底色的方法

1、项目背景 对于不会PS的小伙伴,抠图是一个难度系数想当高的活儿,某宝照片抠图和证件照换底色均价都是5元RMB,所以今天要介绍的这款神工具,只要 3 行代码 5 秒钟就可以完成高精度抠...

浅析Python pandas模块输出每行中间省略号问题

关于Python数据分析中pandas模块在输出的时候,每行的中间会有省略号出现,和行与行中间的省略号....问题,其他的站点(百度)中的大部分都是瞎写,根本就是复制黏贴以前的版本,你要...

PyQt5多线程刷新界面防假死示例

PyQt5多线程刷新界面防假死示例

在做GUI界面时我们希望后台任务能够与UI分开,在PyQt中,主线程用来重绘界面。而子线程里边的实时处理结果需要反馈到界面,子线程里边不能执行界面更新操作。 wxpython多线程刷新界...

python从sqlite读取并显示数据的方法

本文实例讲述了python从sqlite读取并显示数据的方法。分享给大家供大家参考。具体实现方法如下: import cgi, os, sys import sqlite3 as d...

理解Python中的类与实例

面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,...