1
0
forked from tdwojak/Python2017
Python2017/labs05/task04.py

63 lines
1.7 KiB
Python
Raw Normal View History

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-31 13:37:11 +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
def main():
""" main """
2017-12-31 13:37:11 +01:00
parser = argparse.ArgumentParser()
parser.add_argument("-l", help="-l switch returns number of lines", action='store_true')
parser.add_argument("-w", help="-w switch returns number of words", action='store_true')
parser.add_argument("-c", help="-c switch returns number of characters", action='store_true')
parser.add_argument("filename", help="path to a file to read from", type=argparse.FileType('rt'), nargs='?')
args = parser.parse_args()
if args.filename is None:
readinput = sys.stdin.read()
else:
readinput = args.filename.read()
outputmsg = ""
if args.l:
outputmsg = "Number of typed lines: {}".format(count_lines(readinput))
elif args.w:
outputmsg = "Number of typed words: {}".format(count_words(readinput))
elif args.c:
outputmsg = "Number of typed characters: {}".format(count_chars(readinput))
else:
outputmsg = "Number of typed (lines, words, characters): {}".format(wc(readinput))
print(outputmsg)
2017-12-16 06:52:54 +01:00
if __name__ == "__main__":
main()