|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import argparse |
| 4 | + |
| 5 | +# CLI argument parsing |
| 6 | +parser = argparse.ArgumentParser(description="Simplified implementation of wc") |
| 7 | +parser.add_argument("paths", nargs="*", default=["."], help="One or more file or directory paths") |
| 8 | +parser.add_argument("-l", "--line", action="store_true", help="Count lines") |
| 9 | +parser.add_argument("-w", "--word", action="store_true", help="Count words") |
| 10 | +parser.add_argument("-c", "--character", action="store_true", help="Count characters") |
| 11 | + |
| 12 | +args = parser.parse_args() |
| 13 | +file_paths = args.paths |
| 14 | + |
| 15 | +# Fallback: if no options passed, show all |
| 16 | +show_line = args.line |
| 17 | +show_word = args.word |
| 18 | +show_char = args.character |
| 19 | +show_all = not (show_line or show_word or show_char) |
| 20 | + |
| 21 | +# Count content in a string |
| 22 | +def count_content(content): |
| 23 | + lines = content.splitlines() |
| 24 | + words = content.strip().split() |
| 25 | + characters = len(content) |
| 26 | + return len(lines), len(words), characters |
| 27 | + |
| 28 | +# Totals for multiple files |
| 29 | +total = { |
| 30 | + "lines": 0, |
| 31 | + "words": 0, |
| 32 | + "characters": 0 |
| 33 | +} |
| 34 | + |
| 35 | +file_count = 0 |
| 36 | + |
| 37 | +for input_path in file_paths: |
| 38 | + try: |
| 39 | + if os.path.isdir(input_path): |
| 40 | + print(f"{input_path} is a directory. Skipping.") |
| 41 | + continue |
| 42 | + |
| 43 | + with open(input_path, "r", encoding="utf-8") as f: |
| 44 | + content = f.read() |
| 45 | + |
| 46 | + lines, words, characters = count_content(content) |
| 47 | + |
| 48 | + total["lines"] += lines |
| 49 | + total["words"] += words |
| 50 | + total["characters"] += characters |
| 51 | + file_count += 1 |
| 52 | + |
| 53 | + # Prepare output per file |
| 54 | + output_parts = [] |
| 55 | + if show_line or show_all: |
| 56 | + output_parts.append(f"{lines:8}") |
| 57 | + if show_word or show_all: |
| 58 | + output_parts.append(f"{words:8}") |
| 59 | + if show_char or show_all: |
| 60 | + output_parts.append(f"{characters:8}") |
| 61 | + |
| 62 | + output_parts.append(input_path) |
| 63 | + print(" ".join(output_parts)) |
| 64 | + |
| 65 | + except Exception as e: |
| 66 | + print(f'Error reading "{input_path}": {e}', file=sys.stderr) |
| 67 | + |
| 68 | +# Print totals if more than one file processed |
| 69 | +if file_count > 1: |
| 70 | + output_parts = [] |
| 71 | + if show_line or show_all: |
| 72 | + output_parts.append(f"{total['lines']:8}") |
| 73 | + if show_word or show_all: |
| 74 | + output_parts.append(f"{total['words']:8}") |
| 75 | + if show_char or show_all: |
| 76 | + output_parts.append(f"{total['characters']:8}") |
| 77 | + output_parts.append("total") |
| 78 | + print(" ".join(output_parts)) |
0 commit comments