python統(tǒng)計文本文件內單詞數(shù)量的方法
更新時間:2015年05月30日 12:29:49 作者:不吃皮蛋
這篇文章主要介紹了python統(tǒng)計文本文件內單詞數(shù)量的方法,涉及Python針對文本文件及字符串的相關操作技巧,需要的朋友可以參考下
本文實例講述了python統(tǒng)計文本文件內單詞數(shù)量的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
# 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爬取歷年高考數(shù)據(jù)并分析
轉眼間,高考的日子又要來臨了,不知道高考學子們準備的怎么樣了,今天這篇文章簡單且隨意地分析一下高考的一些數(shù)據(jù),需要的朋友可以參考下2021-06-06
Pycharm+Python工程,引用子模塊的實現(xiàn)
這篇文章主要介紹了Pycharm+Python工程,引用子模塊的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Django admin 實現(xiàn)search_fields精確查詢實例
這篇文章主要介紹了Django admin 實現(xiàn)search_fields精確查詢實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Pygame游戲開發(fā)之太空射擊實戰(zhàn)敵人精靈篇
相信大多數(shù)8090后都玩過太空射擊游戲,在過去游戲不多的年代太空射擊自然屬于經典好玩的一款了,今天我們來自己動手實現(xiàn)它,在編寫學習中回顧過往展望未來,下面開始講解敵人精靈的使用2022-08-08

