Grishachev - wc

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, os
try:
#This try-block is a test of correct input.
test = sys.argv[1]
#end of test.
if sys.argv[1] == "-h":
sys.stdout.write("MYWC\nThis function is analog of func 'wc' in Unix-like OS.\nKeys:\n\t-l: count of lines.\n\t-m: count of chars (lenstr).\n\t-w: count of words.\n\t-c: count of bytes\n\t-h: help.\nUsing: \"mywc [key] [file]\" or \"mywc [key]\" if input is in stdin\n")
else:
#In this test program checks STDIN or ARGV input file
try:
if sys.argv[1][0] == '-':
file = sys.argv[2]
else:
file = sys.argv[1]
f = open(file)
a = f.read()
except FileNotFoundError:
sys.stdout.write("File Not Found. Try again.")
finally:
if sys.argv[1] == '-c':
try:
count = os.path.getsize(file)
sys.stdout.write(str(count) + '\n')
except:
count = sys.getsizeof(sys.stdin.read())
sys.stdout.write(str(count) + '\n')
a = sys.stdin.read()
#end
count = 0
# cc = 0
# wc = 0
# lc = 0
#Main function
#try:
if sys.argv[1] == '-l' :
for i in range(0, len(a)) :
if a[i] == '\n':
count = count + 1
if a[len(a)-1] != '\n':
count = count + 1
sys.stdout.write(str(count) + '\n')
if sys.argv[1] == '-m':
count = len(a)
sys.stdout.write(str(count) + '\n')
if sys.argv[1] == '-w' :
for i in range(1, len(a)):
if (a[i-1] != ' ' and a[i-1] != '\n' and a[i-1] != '\t') and (a[i] == ' ' or a[i] == '\n' or a[i] == '\t') :
count = count + 1
if a[len(a)-1] != ' ' and a[len(a)-1] != '\t' and a[len(a)-1] != '\n' :
count = count + 1
sys.stdout.write(str(count) + '\n')
except:
sys.stdout.write("Wrong format. Using: \"mywc [key] [file]\" or \"mywc [key]\" if input is in stdin\n")