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.
|
|
|
|
"""
|
|
|
|
|
2018-01-02 02:45:14 +01:00
|
|
|
import sys, 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):
|
2018-01-02 02:45:14 +01:00
|
|
|
""" return number of characters. """
|
2017-12-16 06:52:54 +01:00
|
|
|
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 """
|
2018-01-02 02:45:14 +01:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('-l', help="number of lines", action="store_true")
|
|
|
|
parser.add_argument('-w', help="number of words", action="store_true")
|
|
|
|
parser.add_argument('-c', help="number of characters", action="store_true")
|
|
|
|
parser.add_argument('fn', nargs='?', type=file, default=sys.stdin, help='optional filename to read from')
|
|
|
|
args = parser.parse_args()
|
|
|
|
lines, words, chars = wc(args.fn.read())
|
|
|
|
if( args.l or args.w or args.c ):
|
|
|
|
if(args.l):
|
|
|
|
print(lines)
|
|
|
|
if(args.w):
|
|
|
|
print(words)
|
|
|
|
if(args.c):
|
|
|
|
print(chars)
|
|
|
|
else:
|
|
|
|
print(lines, words, chars)
|
2017-12-16 06:52:54 +01:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|