#!/usr/bin/python
Import OS Import Sys 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= "Show total or not") 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, lines, words, chars, fn): If Options.lines: Print lines, If Options.words: Print words, If Options.chars: Print chars, PRINT fn
def main (): options, args = opt () If not (Options.lines or options.words or options.chars): Options.lines, options.lines, 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 >> Sys.stderr, "%s:is a directory"% fn Else Sys.stderr.write ("%s:no such file or directory\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)
Main () |