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

相关文章

TF-IDF与余弦相似性的应用(二) 找出相似文章

TF-IDF与余弦相似性的应用(二) 找出相似文章

上一次,我用TF-IDF算法自动提取关键词。 今天,我们再来研究另一个相关的问题。有些时候,除了找到关键词,我们还希望找到与原文章相似的其他文章。比如,"Google新闻"在主新闻下方...

python获取磁盘号下盘符步骤详解

python获取磁盘号下盘符步骤详解

这次主要教的是如何通过Python 获取Windows系统下的所有的磁盘盘符,以列表的形式展示出来,获取磁盘号下的盘符包括能够获取到我们正在插在电脑上的U盘,也可以读取到,希望能够对你们...

Django项目使用CircleCI的方法示例

Django项目使用CircleCI的方法示例

自从认识了 CircleCI 之后,基本上都在用这个了。相比于之前用的travis-ci ,CircleCI 丑是丑了点,但是相比与 travis 有几点好处: CircleCI...

纯python实现机器学习之kNN算法示例

纯python实现机器学习之kNN算法示例

前面文章分别简单介绍了线性回归,逻辑回归,贝叶斯分类,并且用python简单实现。这篇文章介绍更简单的 knn, k-近邻算法(kNN,k-NearestNeighbor)。 k-近邻...

Python绘制热力图示例

Python绘制热力图示例

本文实例讲述了Python绘制热力图操作。分享给大家供大家参考,具体如下: 示例一: # -*- coding: utf-8 -*- from pyheatmap.heatmap i...