python統(tǒng)計(jì)文本文件內(nèi)單詞數(shù)量的方法
本文實(shí)例講述了python統(tǒng)計(jì)文本文件內(nèi)單詞數(shù)量的方法。分享給大家供大家參考。具體實(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()
希望本文所述對(duì)大家的python程序設(shè)計(jì)有所幫助。
相關(guān)文章
高考要來(lái)啦!用Python爬取歷年高考數(shù)據(jù)并分析
轉(zhuǎn)眼間,高考的日子又要來(lái)臨了,不知道高考學(xué)子們準(zhǔn)備的怎么樣了,今天這篇文章簡(jiǎn)單且隨意地分析一下高考的一些數(shù)據(jù),需要的朋友可以參考下2021-06-06
Pycharm+Python工程,引用子模塊的實(shí)現(xiàn)
這篇文章主要介紹了Pycharm+Python工程,引用子模塊的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
對(duì)Python信號(hào)處理模塊signal詳解
今天小編就為大家分享一篇對(duì)Python信號(hào)處理模塊signal詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
python將dict中的unicode打印成中文實(shí)例
這篇文章主要介紹了python將dict中的unicode打印成中文實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
Django admin 實(shí)現(xiàn)search_fields精確查詢(xún)實(shí)例
這篇文章主要介紹了Django admin 實(shí)現(xiàn)search_fields精確查詢(xún)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
教你用scrapy框架爬取豆瓣讀書(shū)Top250的書(shū)類(lèi)信息
這篇文章主要介紹了教你用scrapy框架爬取豆瓣讀書(shū)Top250的書(shū)類(lèi)信息,文中提供了解決思路和部分實(shí)現(xiàn)代碼,需要的朋友可以參考下2023-03-03
python檢測(cè)主機(jī)的連通性并記錄到文件的實(shí)例
今天小編就為大家分享一篇python檢測(cè)主機(jī)的連通性并記錄到文件的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
Pygame游戲開(kāi)發(fā)之太空射擊實(shí)戰(zhàn)敵人精靈篇
相信大多數(shù)8090后都玩過(guò)太空射擊游戲,在過(guò)去游戲不多的年代太空射擊自然屬于經(jīng)典好玩的一款了,今天我們來(lái)自己動(dòng)手實(shí)現(xiàn)它,在編寫(xiě)學(xué)習(xí)中回顧過(guò)往展望未來(lái),下面開(kāi)始講解敵人精靈的使用2022-08-08
python eval 轉(zhuǎn)換k m到乘法計(jì)算的操作
這篇文章主要介紹了python eval 轉(zhuǎn)換k m到乘法計(jì)算的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
解決python3 urllib 鏈接中有中文的問(wèn)題
今天小編就為大家分享一篇解決python3 urllib 鏈接中有中文的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07

