1+ import argparse
2+ import sys
3+ import os
4+
5+ parser = argparse .ArgumentParser (
6+ prog = "wc" ,
7+ description = "Print newline, word, and byte counts for files"
8+ )
9+
10+ parser .add_argument (
11+ "-l" ,
12+ "--lines" ,
13+ action = "store_true" ,
14+ help = "Print the newline counts"
15+ )
16+
17+ parser .add_argument (
18+ "-w" ,
19+ "--words" ,
20+ action = "store_true" ,
21+ help = "Print the word counts"
22+ )
23+
24+ parser .add_argument (
25+ "-c" ,
26+ "--bytes" ,
27+ action = "store_true" ,
28+ help = "Print the byte counts"
29+ )
30+
31+ parser .add_argument (
32+ "paths" ,
33+ nargs = "*" ,
34+ help = "The file to print"
35+ )
36+
37+ args = parser .parse_args ()
38+
39+ total_line_count = 0
40+ total_word_count = 0
41+ total_byte_count = 0
42+
43+ rows = []
44+
45+ def get_counts (path ):
46+ with open (path , "r" ) as file :
47+ content = file .readlines ()
48+
49+ lines_count = len (content )
50+
51+ joined_content = "" .join (content )
52+
53+ words = joined_content .split ()
54+ word_count = len (words )
55+
56+ byte_count = len (joined_content .encode ())
57+
58+ return lines_count , word_count , byte_count
59+
60+
61+ def select_count (lines_count , word_count , byte_count ):
62+ selected_counts = []
63+
64+ if args .lines :
65+ selected_counts .append (lines_count )
66+
67+ if args .words :
68+ selected_counts .append (word_count )
69+
70+ if args .bytes :
71+ selected_counts .append (byte_count )
72+
73+ if len (selected_counts ) == 0 :
74+ selected_counts .append (lines_count )
75+ selected_counts .append (word_count )
76+ selected_counts .append (byte_count )
77+
78+ return selected_counts
79+
80+
81+ for path in args .paths :
82+ lines_count , word_count , byte_count = get_counts (path )
83+
84+ total_line_count += lines_count
85+ total_word_count += word_count
86+ total_byte_count += byte_count
87+
88+ selected_counts = select_count (
89+ str (lines_count ),
90+ str (word_count ),
91+ str (byte_count )
92+ )
93+
94+ rows .append ((selected_counts , path ))
95+
96+ if len (args .paths ) > 1 :
97+ total_counts = select_count (
98+ str (total_line_count ),
99+ str (total_word_count ),
100+ str (total_byte_count )
101+ )
102+ rows .append ((total_counts , "total" ))
103+
104+ padding = max (
105+ len (count )
106+ for counts , _ in rows
107+ for count in counts
108+ )
109+
110+ output = []
111+
112+ for counts , path in rows :
113+ padded_counts = []
114+
115+ for count in counts :
116+ padded_counts .append (count .rjust (padding ))
117+
118+ output .append (" " .join (padded_counts ) + " " + path )
119+
120+ print ("\n " .join (output ))
0 commit comments