1
0
forked from tdwojak/Python2017
Python2017/labs05/task04.py
s45146 ef426e0c64 Zadanie domowe Zad4
Labs05 - task04
Rozwiązanie s45146
2017-12-20 21:03:42 +01:00

80 lines
2.2 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
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 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
#Moja klasa wyjątku
class ArgException(Exception):
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
def main():
""" main """
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, "\nToo many arguments passed!")
#print(args.l, args.w, args.c, args.input)
return
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, "\nError in arguments!")
#print(wc(sys.stdin.read()))
# print(wc(fh_lines))
#print(fh_lines)
print(res)
if __name__ == "__main__":
main()