首页 > 代码库 > python版wc
python版wc
#!/usr/bin/env python
#coding:utf8
from optparse import OptionParser
import sys, os
#parser = OptionParser()
def set():
parser = OptionParser("Usage: %prog [file1] [file2]...")
parser.add_option("-c",
"--chars",
dest="characters",
action="store_true",
default=False,
help="only count characters",
)
parser.add_option("-w",
"--words",
dest="words",
action="store_true",
default=False,
help="only count words",
)
parser.add_option("-l",
"--lines",
dest="lines",
action="store_true",
default=False,
help="only count lines",
)
parser.add_option("-n",
"--no-total",
dest="nototal",
action="store_true",
default=False,
help="only count not total",
)
return parser.parse_args()
class Count_file(object):
l,w,le,lens,wo,lines=0,0,0,0,0,0
nu=" "*5
def get_count(self):
self.lens=len(data)
self.wo=len(data.split())
self.lines=data.count("\n")
def print_wc(self):
if options.characters:
print self.lines,
self.l += self.lines
if options.words:
print self.wo,
self.w += self.wo
if options.lines:
print self.lens,
self.le += self.lens
try:
print args[i]
except:
print "stdin"
def print_total(self):
if options.nototal:
pass
else:
if len(args)>1:
for i in (self.l,self.w,self.le):
if i ==0:
pass
else:
print i,
print "总用量"
def print_fi_pa(self):
print __file__,":",args[i],":"+"没有那个文件或目录!"
def print_path(self):
print __file__,":",args[i],":"+"是一个目录"
print self.nu,self.l,self.nu,self.w,self.nu,self.le,args[i]
if __name__ =="__main__":
options,args = set()
test=Count_file()
if (options.characters or options.words or options.lines):
pass
else:
options.characters, options.words, options.lines= True, True, True
if args:
for i in xrange(len(args)):
if os.path.isfile(args[i]):
data=http://www.mamicode.com/file(args[i]).read()
test.get_count()
test.print_wc()
elif os.path.isdir(args[i]):
test.print_path()
else:
test.print_fi_pa()
test.print_total()
else:
data=http://www.mamicode.com/sys.stdin.read()
test.get_count()
test.print_wc()
本文出自 “原创python发布区” 博客,请务必保留此出处http://cuihailong.blog.51cto.com/2923450/1409566