Skip to content

Commit 88f8402

Browse files
committed
Complete wc.py
1 parent c64c5dd commit 88f8402

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import sys
2+
import argparse
3+
import os
4+
5+
parser = argparse.ArgumentParser(
6+
prog="wc",
7+
description="Word count",
8+
)
9+
10+
parser.add_argument("-l", action="store_true", help="Count lines")
11+
parser.add_argument("-w", action="store_true", help="Count words")
12+
parser.add_argument("-c", action="store_true", help="Count bytes")
13+
parser.add_argument("paths", nargs="+", help="The files to process")
14+
15+
args = parser.parse_args()
16+
17+
totalLines = 0
18+
totalWords = 0
19+
totalBytes = 0
20+
21+
for path in args.paths:
22+
try:
23+
with open(path, "rb") as f:
24+
buffer = f.read()
25+
content = buffer.decode("utf-8") #, errors="ignore"
26+
27+
lines = len(content.split("\n")) - 1
28+
wordCount = len(content.strip().split())
29+
bytes = len(buffer)
30+
31+
totalLines += lines
32+
totalWords += wordCount
33+
totalBytes += bytes
34+
35+
if args.l:
36+
print(f"{lines} {path}")
37+
elif args.w:
38+
print(f"{wordCount} {path}")
39+
elif args.c:
40+
print(f"{bytes} {path}")
41+
else:
42+
print(f"{lines} {wordCount} {bytes} {path}")
43+
except Exception as e:
44+
print(f"Error reading {path}: {e}")
45+
46+
if len(args.paths) > 1:
47+
if args.l:
48+
print(f"{totalLines} total")
49+
elif args.w:
50+
print(f"{totalWords} total")
51+
elif args.c:
52+
print(f"{totalBytes} total")
53+
else:
54+
print(f"{totalLines} {totalWords} {totalBytes} total")

0 commit comments

Comments
 (0)