Ex1:Counting Words
import string
def numwords(s):
list = string.split(s)
return len(list)
inp = open("menu.txt","r")
total = 0
for line in inp.readlines():
total = total + numwords(line)
print "File had %d words" % total
inp.close()
Ex2:Counting Word、Lines 、Characters
import string, sys
if len(sys.argv) != 2:
name = raw_input("Enter the file name: ")
else:
name = sys.argv[1]
inp = open(name,"r")
words = 0
lines = 0
chars = 0
for line in inp.readlines():
lines = lines + 1
list = string.split(line)
words = words + len(list)
chars = len(line)
print "%s has %s lines, %d words and %d characters" % (name,lines,words,chars)
inp.close()