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

相关文章

解决pandas无法在pycharm中使用plot()方法显示图像的问题

最近用了pycharm,感觉还不错,就是pandas中Series、DataFrame的plot()方法不显示图片就给我结束了,但是我在ipython里就能画图 以前的代码是这样的...

详解用Python练习画个美队盾牌

详解用Python练习画个美队盾牌

0 环境 Python版本:3.6.6 操作系统:Mac OS Mojave 10.14.2 1 引言 最近我媳妇每天晚上吃饭时候也拿手机看,上厕所也在看。 看着看着还会笑?WTF?你...

Python实现压缩与解压gzip大文件的方法

本文实例讲述了Python实现压缩与解压gzip大文件的方法。分享给大家供大家参考,具体如下: #encoding=utf-8 #author: walker #date: 2015...

python3使用pyqt5制作一个超简单浏览器的实例

我们使用的是QWebview模块,这里也主要是展示下QWebview的用法。 之前在网上找了半天的解析网页的内容,都不是很清楚。 这是核心代码: webview = Qwebview...

使用pyinstaller逆向.pyc文件

使用pyinstaller逆向.pyc文件

搭建python环境 1.百度搜索python3.7下载,找到官网下载安装包,运行安装包并配置环境变量。 2.这里一定要安装python3.7版本的,我之前安装python...