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 字典 setdefault()和get()方法比较详解

python 字典 setdefault()和get()方法比较详解

dict.setdefault(key, default=None) --> 有key获取值,否则设置 key:default,并返回default,default默认值为None...

tensorflow没有output结点,存储成pb文件的例子

tensorflow没有output结点,存储成pb文件的例子

Tensorflow中保存成pb file 需要 使用函数 graph_util.convert_variables_to_constants(sess, sess.graph_def,...

python使用Plotly绘图工具绘制散点图、线形图

python使用Plotly绘图工具绘制散点图、线形图

今天在研究Plotly绘制散点图的方法,供大家参考,具体内容如下 使用Python3.6 + Plotly Plotly版本2.0.0 在开始之前先说说,还需要安装库Numpy,安装方法...

Python使用Slider组件实现调整曲线参数功能示例

Python使用Slider组件实现调整曲线参数功能示例

本文实例讲述了Python使用Slider组件实现调整曲线参数功能。分享给大家供大家参考,具体如下: 一 代码 import numpy as np import matplotli...

Python实现的几个常用排序算法实例

前段时间为准备百度面试恶补的东西,虽然最后还是被刷了,还是把那几天的“战利品”放点上来,算法一直是自己比较薄弱的地方,以后还要更加努力啊。 下面用Python实现了几个常用的排序,如快速...