43tt 发表于 2014-5-12 09:37:37

python版wc

#!/usr/bin/env python
#coding:utf8
from optparse import OptionParser
import sys, os
#parser = OptionParser()
def set():
   parser = OptionParser("Usage: %prog ...")
   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
       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,":"+"没有那个文件或目录!"
   def print_path(self):
       print __file__,":",args,":"+"是一个目录"
       print self.nu,self.l,self.nu,self.w,self.nu,self.le,args
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):
               data=file(args).read()
               test.get_count()
               test.print_wc()
         elif os.path.isdir(args):
               test.print_path()
         else:
               test.print_fi_pa()
       test.print_total()
   else:
       data=sys.stdin.read()
       test.get_count()
       test.print_wc()

页: [1]
查看完整版本: python版wc