2017-12-16 06:52:54 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Implementacja narzedzia ` ` wc ` ` z linuksa ( word counter ) .
Zwraca liczbę słów , znaków i linii .
"""
import sys
2017-12-20 21:03:42 +01:00
import argparse
2017-12-16 06:52:54 +01:00
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 words. """
return len ( text )
def wc ( text ) :
""" proper wc """
lines = count_lines ( text )
words = count_words ( text )
chars = count_chars ( text )
return lines , words , chars
2017-12-20 21:03:42 +01:00
#Moja klasa wyjątku
class ArgException ( Exception ) :
def __init__ ( self , text ) :
self . text = text
def __str__ ( self ) :
return self . text
2017-12-16 06:52:54 +01:00
def main ( ) :
""" main """
2017-12-20 21:03:42 +01:00
msg_usage = " Usage: task04.py [-h | -l | -w | -c] [file_name | stdin] "
parser = argparse . ArgumentParser ( )
parser . add_argument ( " -l " , help = " -l returns number of lines " , action = ' store_true ' )
parser . add_argument ( " -w " , help = " -w returns number of words " , action = ' store_true ' )
parser . add_argument ( " -c " , help = " -c returns number of characters " , action = ' store_true ' )
parser . add_argument ( " file_name " , help = " This is path to the text input file to read the lines from or stdin if not given " , type = argparse . FileType ( ' rt ' ) , nargs = ' ? ' )
args = parser . parse_args ( )
if args . l + args . w + args . c > 1 : #Jeśli więcej niż 1 argument {-l, -w, -c}
print ( msg_usage , " \n Too many arguments passed! " )
#print(args.l, args.w, args.c, args.input)
return
2017-12-16 06:52:54 +01:00
2017-12-20 21:03:42 +01:00
res = " " #Zwracany napis
if args . file_name is None :
fh_lines = sys . stdin . read ( )
else :
fh_lines = args . file_name . read ( )
if args . l :
res = count_lines ( fh_lines )
elif args . w :
res = count_words ( fh_lines )
elif args . c :
res = count_chars ( fh_lines )
elif not ( args . l and args . w and args . c ) :
res = wc ( fh_lines )
else : #Coś jest nie tak!
raise ArgException ( msg_usage , " \n Error in arguments! " )
#print(wc(sys.stdin.read()))
# print(wc(fh_lines))
#print(fh_lines)
print ( res )
2017-12-16 06:52:54 +01:00
if __name__ == " __main__ " :
main ( )