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开发WebService系列教程之REST,web.py,eurasia,Django

在Bioinformatics(生物信息学)领域,WebService是很重要的一种数据交换技术,未来必将更加重要。目前EBI所提供的WebService就分别有SOAP和REST两种方...

django中send_mail功能实现详解

前言 我们大家应该都知道python中smtplib模块用于邮件的功能,而django对这个这模块进行封装,使得它使用起来十分简单。 django.core.mail就是django邮件...

Django对models里的objects的使用详解

首先我们先熟悉下objects的大致概念. object是模型属性---用于模型对象和数据库交互 . objects = Manager() 是管理器类型的对象 ,是Model和数据库进...

Centos Python2 升级到Python3的简单实现

1. 从Python官网到获取Python3的包, 切换到目录/usr/local/src #wget https://www.python.org/ftp/python/3.5.1...

使用pandas批量处理矢量化字符串的实例讲解

进行已经矢量化后的字符串数据,可以使用pandas的Series数据对象的map方法。这样,对于未经矢量化的数据也可以先进行数据的矢量化转换然后再进行相应的处理。 举例实现字符串数据的操...