forked from tdwojak/Python2017
63 lines
1.5 KiB
Python
63 lines
1.5 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
|
|
|
|
|
|
def main():
|
|
""" main """
|
|
print(wc(sys.stdin.read()))
|
|
|
|
parse = argparse.ArgumentParser()
|
|
parse.add_argument('--l', help = 'number of lines', action = 'store_true')
|
|
parse.add_argument('--w', help = 'number of words', action = 'store_true')
|
|
parse.add_argument('--c', help = 'number of characters', action = 'store_true')
|
|
parse.add_argument('file', help = 'filepath', type = argparse.FileType('f'), nargs = '?')
|
|
args = parse.parse_args()
|
|
|
|
if args.file is None:
|
|
opt = sys.stdin.read()
|
|
else:
|
|
opt = args.file.read()
|
|
|
|
if args.l:
|
|
output = count_lines(opt)
|
|
elif args.w:
|
|
output = count_words(opt)
|
|
elif args.c:
|
|
output = count_chars(opt)
|
|
else:
|
|
output = wc(opt)
|
|
|
|
print(output)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|