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 将json序列化后的字符串转换成字典(推荐)

一般而言下面的就可以完成需求了。 def convertToDic(data): jsonDic=json.loads(data) return dict(jsonDic) 但...

机器学习10大经典算法详解

本文为大家分享了机器学习10大经典算法,供大家参考,具体内容如下 1、C4.5 C4.5算法是机器学习算法中的一种分类决策树算法,其核心算法是ID3算法.  C4.5算法继承了...

Python画图高斯分布的示例

如下所示: import matplotlib.pyplot as plt import numpy as np import math def gaussian(sigma, x,...

Python 3中print函数的使用方法总结

前言 Python 思想:“一切都是对象!”,最近发现python3和python2中print的用法有很多不同,python3中需要使用括号,缩进要使用4个空格(这不是必须的,但你最好...

python使用Plotly绘图工具绘制水平条形图

python使用Plotly绘图工具绘制水平条形图

本文实例为大家分享了python绘制水平条形图的具体代码,供大家参考,具体内容如下 水平条形图与绘制柱状图类似,大家可以先看看我之前写的博客,如何绘制柱状图 水平条形图需要在Bar函数中...