11import argparse
22
3- # Setup argument parser
4- parser = argparse .ArgumentParser (
5- prog = "wc" ,
6- description = "Count lines, words, and characters"
7- )
3+ parser = argparse .ArgumentParser (prog = "wc" , description = "Count lines, words, and characters" )
84parser .add_argument ("paths" , nargs = '+' , help = "Files to count" )
9- parser .add_argument ("-l" , "--lines" , action = "store_true" , help = "Count lines only" )
10- parser .add_argument ("-w" , "--words" , action = "store_true" , help = "Count words only" )
11- parser .add_argument ("-c" , "--chars" , action = "store_true" , help = "Count characters only" )
5+ parser .add_argument ("-l" , "--lines" , action = "store_true" )
6+ parser .add_argument ("-w" , "--words" , action = "store_true" )
7+ parser .add_argument ("-c" , "--chars" , action = "store_true" )
128
139args = parser .parse_args ()
1410
15- # Track totals
16- total_lines = 0
17- total_words = 0
18- total_chars = 0
11+ # If no flags are provided, the default behavior is to show all three
12+ show_all = not ( args . lines or args . words or args . chars )
13+
14+ total_stats = [ 0 , 0 , 0 ] # lines, words, chars
1915
2016for path in args .paths :
21- # Read the file
2217 with open (path , "r" ) as f :
2318 content = f .read ()
2419
25- # Count lines, words, characters
26- lines = len (content .rstrip ('\n ' ).split ('\n ' ))
27- words = len (content .split ())
28- chars = len (content )
29-
30- # Add to totals
31- total_lines += lines
32- total_words += words
33- total_chars += chars
34-
35- if args .lines :
36- print (f"{ lines :8} { path } " )
37- elif args .words :
38- print (f"{ words :8} { path } " )
39- elif args .chars :
40- print (f"{ chars :8} { path } " )
41- else :
42- print (f"{ lines :8} { words :8} { chars :8} { path } " )
43-
44-
45- # Print totals if multiple files
46- if len (args .paths ) > 1 :
47- if args .lines :
48- print (f"{ total_lines :8} total" )
49- elif args .words :
50- print (f"{ total_words :8} total" )
51- elif args .chars :
52- print (f"{ total_chars :8} total" )
53- else :
54- print (f"{ total_lines :8} { total_words :8} { total_chars :8} total" )
20+ stats = [
21+ len (content .splitlines ()),
22+ len (content .split ()),
23+ len (content )
24+ ]
25+
26+ for i in range (3 ):
27+ total_stats [i ] += stats [i ]
28+
29+ output = []
30+ if args .lines or show_all : output .append (f"{ stats [0 ]:8} " )
31+ if args .words or show_all : output .append (f"{ stats [1 ]:8} " )
32+ if args .chars or show_all : output .append (f"{ stats [2 ]:8} " )
33+
34+ print (f"{ '' .join (output )} { path } " )
5535
36+ if len (args .paths ) > 1 :
37+ total_output = []
38+ if args .lines or show_all : total_output .append (f"{ total_stats [0 ]:8} " )
39+ if args .words or show_all : total_output .append (f"{ total_stats [1 ]:8} " )
40+ if args .chars or show_all : total_output .append (f"{ total_stats [2 ]:8} " )
41+
42+ print (f"{ '' .join (total_output )} total" )
0 commit comments