ywg 发表于 2018-8-16 09:46:04

用python的optparse模块实现wc的功能

#!/usr/bin/env python  
#coding:utf-8
  
#对标准输入进行统计
  
import sys, os
  
from optparse import OptionParser
  

  
def opt():
  
    parser = OptionParser()
  
    parser.add_option("-c", "--char",
  
                  dest="chars",
  
                  action="store_true",
  
                  default=False,
  
                  help="only count chars")
  
    parser.add_option("-w", "--word",
  
                  dest="words",
  
                  action="store_true",
  
                  default=False,
  
                  help="only count words")
  
    parser.add_option("-l", "--line",
  
                  dest="lines",
  
                  action="store_true",
  
                  default=False,
  
                  help="only count lines")
  
    parser.add_option("-n", "--nototal",
  
                  dest="nototal",
  
                  action="store_true",
  
                  default=False,
  
                  help="nototal")
  
    options, args = parser.parse_args()
  
    return options, args
  

  
#定义统计函数
  
def get_Count(data):
  
    chars = len(data)
  
    words = len(data.split())
  
    lines = data.count('\n')
  
    return lines, words, chars
  

  
#定义打印函数,
  
def print_wc(options, words, chars, lines, fn):
  
    if options.chars:
  
      print chars,
  
    if options.words:
  
      print words,
  
    if options.lines:
  
      print lines,
  
    print fn
  

  
#定义主函数,注意这里的主函数和c中main函数不一样。
  
def main():
  
    options, args = opt()
  
    if not (options.lines or options.words or options.chars):#默认是三个全部有的,就是命令参数不写,默认三个全有
  
      options.lines, options.words, options.chars = True, True, True
  
    if args:
  
      total_lines, total_words, total_chars = 0, 0, 0
  
      for fn in args:
  
            if os.path.isfile(fn):
  
                with open(fn) as fd:
  
                  data = fd.read()
  
                lines, words, chars = get_Count(data)
  
                print_wc(options, lines, words, chars, fn)
  
                total_lines += lines
  
                total_words += words
  
                total_chars += chars
  
            elif os.path.isdir(fn):
  
               # print "The %s is a directory" % fn
  
                print >> sys.stderr, "The %s is a directory" % fn#标准错误输出方法一
  
            else:
  
                sys.stderr.write("The %s No such file or directoryi\n" % fn) #标准错误输出二
  
      if len(args) > 1:
  
            if not options.nototal:
  
                print_wc(options, total_lines, total_words, total_chars, 'total')
  
    else:#从标准输入读取数据
  
      data = sys.stdin.read()
  
      fn = " "
  
      lines, words, chars = get_Count(data)
  
      print_wc(options, lines, words, chars, fn)
  

  
if __name__ == "__main__":
  
    main()


页: [1]
查看完整版本: 用python的optparse模块实现wc的功能