30 lines
694 B
Python
Executable File
30 lines
694 B
Python
Executable File
#!/usr/bin/env python3
|
|
"""Word counter utility - counts words in a file or from stdin."""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def count_words(text: str) -> int:
|
|
"""Count words in text (split on whitespace)."""
|
|
return len(text.split())
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) > 1:
|
|
# Count words in file
|
|
path = Path(sys.argv[1])
|
|
if not path.exists():
|
|
print(f"Error: File not found: {sys.argv[1]}", file=sys.stderr)
|
|
sys.exit(1)
|
|
text = path.read_text()
|
|
else:
|
|
# Count words from stdin
|
|
text = sys.stdin.read()
|
|
|
|
count = count_words(text)
|
|
print(f"Word count: {count}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |