python統(tǒng)計文本文件內(nèi)單詞數(shù)量的方法
更新時間:2015年05月30日 12:29:49 作者:不吃皮蛋
這篇文章主要介紹了python統(tǒng)計文本文件內(nèi)單詞數(shù)量的方法,涉及Python針對文本文件及字符串的相關(guān)操作技巧,需要的朋友可以參考下
本文實(shí)例講述了python統(tǒng)計文本文件內(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()
希望本文所述對大家的python程序設(shè)計有所幫助。
相關(guān)文章
Django 中自定義 Admin 樣式與功能的實(shí)現(xiàn)方法
這篇文章主要介紹了Django 中自定義 Admin 樣式與功能的實(shí)現(xiàn)方法,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07解決python3運(yùn)行selenium下HTMLTestRunner報錯的問題
今天小編就為大家分享一篇解決python3運(yùn)行selenium下HTMLTestRunner報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12Django 解決model 反向引用中的related_name問題
這篇文章主要介紹了Django 解決model 反向引用中的related_name問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python 基于wxpy庫實(shí)現(xiàn)微信添加好友功能(簡潔)
這篇文章主要介紹了Python 基于wxpy庫實(shí)現(xiàn)微信添加好友功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11Python實(shí)現(xiàn)的網(wǎng)頁截圖功能【PyQt4與selenium組件】
這篇文章主要介紹了Python實(shí)現(xiàn)的網(wǎng)頁截圖功能,結(jié)合實(shí)例形式分別描述了使用PyQt4組件與selenium組件進(jìn)行網(wǎng)頁截圖操作的相關(guān)實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下2018-07-07