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-26 15:37:41 +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-26 15:37:41 +01:00
|
|
|
#print(wc(sys.stdin.read()))
|
|
|
|
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument("--l", help="liczba linii", action = 'store_true')
|
|
|
|
parser.add_argument("--w", help="liczba slow", action = 'store_true')
|
|
|
|
parser.add_argument("--c", help="liczba znakow", action = 'store_true')
|
|
|
|
parser.add_argument("file", help="sciezka do pliku", type = argparse.FileType('r'), nargs = '?')
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
|
|
if args.file is None:
|
|
|
|
fh_lines = sys.stdin.read()
|
|
|
|
else:
|
|
|
|
fh_lines = args.file.read()
|
|
|
|
|
|
|
|
if args.l:
|
|
|
|
output = count_lines(fh_lines)
|
|
|
|
elif args.w:
|
|
|
|
output = count_words(fh_lines)
|
|
|
|
elif args.c:
|
|
|
|
output = count_chars(fh_lines)
|
|
|
|
elif not (args.l and args.w and args.c):
|
|
|
|
output = wc(fh_lines)
|
|
|
|
|
|
|
|
print(output)
|
|
|
|
|
2017-12-16 06:52:54 +01:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|