1
0
forked from tdwojak/Python2017
Python2017/labs05/task04.py
2018-01-26 14:43:35 +01:00

55 lines
1.4 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Implementacja narzedzia ``wc`` z linuksa (word counter).
Zwraca liczbę słów, znaków i linii.
"""
import sys, 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 characters", action="store_true")
parser.add_argument('fn', nargs='?', type=file, default=sys.stdin, help='optional filename to read from')
args = parser.parse_args()
lines, words, chars = wc(args.fn.read())
if( args.l or args.w or args.c ):
if(args.l):
print(lines)
if(args.w):
print(words)
if(args.c):
print(chars)
else:
print(lines, words, chars)
if __name__ == "__main__":
main()