|
| 1 | +import sys |
| 2 | + |
| 3 | +args = sys.argv[1:] |
| 4 | + |
| 5 | +show_lines = "-l" in args |
| 6 | +show_words = "-w" in args |
| 7 | +show_bytes = "-c" in args |
| 8 | + |
| 9 | +files = [arg for arg in args if not arg.startswith("-")] |
| 10 | + |
| 11 | +def get_stats(text): |
| 12 | + return { |
| 13 | + "lines": text.count("\n"), |
| 14 | + "words": len(text.split()), |
| 15 | + "bytes": len(text.encode("utf-8")) |
| 16 | + } |
| 17 | + |
| 18 | +def format_num(num): |
| 19 | + return str(num).rjust(8) |
| 20 | + |
| 21 | +total_lines = 0 |
| 22 | +total_words = 0 |
| 23 | +total_bytes = 0 |
| 24 | + |
| 25 | +for file in files: |
| 26 | + with open(file, "r") as f: |
| 27 | + content = f.read() |
| 28 | + |
| 29 | + stats = get_stats(content) |
| 30 | + |
| 31 | + total_lines += stats["lines"] |
| 32 | + total_words += stats["words"] |
| 33 | + total_bytes += stats["bytes"] |
| 34 | + |
| 35 | + output = [] |
| 36 | + |
| 37 | + if show_lines: |
| 38 | + output.append(format_num(stats["lines"])) |
| 39 | + elif show_words: |
| 40 | + output.append(format_num(stats["words"])) |
| 41 | + elif show_bytes: |
| 42 | + output.append(format_num(stats["bytes"])) |
| 43 | + else: |
| 44 | + output.extend([ |
| 45 | + format_num(stats["lines"]), |
| 46 | + format_num(stats["words"]), |
| 47 | + format_num(stats["bytes"]) |
| 48 | + ]) |
| 49 | + |
| 50 | + output.append(file) |
| 51 | + |
| 52 | + print(" ".join(output)) |
| 53 | + |
| 54 | +if len(files) > 1: |
| 55 | + output = [] |
| 56 | + |
| 57 | + if show_lines: |
| 58 | + output.append(format_num(total_lines)) |
| 59 | + elif show_words: |
| 60 | + output.append(format_num(total_words)) |
| 61 | + elif show_bytes: |
| 62 | + output.append(format_num(total_bytes)) |
| 63 | + else: |
| 64 | + output.extend([ |
| 65 | + format_num(total_lines), |
| 66 | + format_num(total_words), |
| 67 | + format_num(total_bytes) |
| 68 | + ]) |
| 69 | + |
| 70 | + output.append("total") |
| 71 | + |
| 72 | + print(" ".join(output)) |
0 commit comments