Count Lines, Sentences, And Words Of A Text File
Join the DZone community and get the full member experience.
Join For Freeโ
# 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()
โ
Opinions expressed by DZone contributors are their own.
Comments