import sys import argparse def count_lines(text): """ return number of lines. """ return len(text.strip().split('\n')) def count_words(text): """ return number of words. """ return sum([len([1 for word in line.split(' ') if len(word)]) for line in text.split('\n')]) def count_chars(text): """ return number of characters. """ return len(text) def wc(text): """ proper wc """ lines = count_lines(text) words = count_words(text) chars = count_chars(text) return lines, words, chars def main(): """ main """ parser = argparse.ArgumentParser() parser.add_argument('-l', help="number of lines", action="store_true") parser.add_argument('-w', help="number of words", action="store_true") parser.add_argument('-c', help="number of chars", action="store_true") parser.add_argument('-filename', type=argparse.FileType('r'), default='-', help='filename to read from') args = parser.parse_args() if args.filename: lines, words, chars = wc(args.filename.read()) elif not sys.stdin.isatty(): lines, words, chars = wc(args.stdin.read()) else: pass if(args.l): print(lines) elif(args.w): print(words) elif(args.c): print(chars) else: print(lines, words, chars) if __name__ == "__main__": main()