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

相关文章

Python3.5基础之函数的定义与使用实例详解【参数、作用域、递归、重载等】

Python3.5基础之函数的定义与使用实例详解【参数、作用域、递归、重载等】

本文实例讲述了Python3.5函数的定义与使用。分享给大家供大家参考,具体如下: 1、函数学习框架 2、函数的定义与格式 (1)定义 (2)函数调用 注:函数名称...

对Django外键关系的描述

注:本文需要你有一定的数据库知识,本文的数据库语法使用mysql书写 Django中,跟外键有关的关系有三种,下面来一一介绍。 OneToManyField 这种最好理解,说白了就是最普...

Django实现简单分页功能的方法详解

本文实例讲述了Django实现简单分页功能的方法。分享给大家供大家参考,具体如下: 使用django的第三方模块django-pure-pagination 安装模块: pip in...

Python实现将一个大文件按段落分隔为多个小文件的简单操作方法

本文实例讲述了Python实现将一个大文件按段落分隔为多个小文件的简单操作方法。分享给大家供大家参考,具体如下: 今天帮同学处理一点语料。语料文件有点大,并且是以连续两个换行符作为段落标...

python numpy和list查询其中某个数的个数及定位方法

1. list 查询个数: 调用list.count(obj)函数,返回obj在list中的个数。 输入: list_a = [2 for x in range(5)] print(...