31 lines
830 B
Python
31 lines
830 B
Python
#!/usr/bin/env python3
|
|
"""Word count utility - counts words in a file and outputs JSON result."""
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
def word_count(filepath):
|
|
"""Count words in file and return stats."""
|
|
path = Path(filepath)
|
|
if not path.exists():
|
|
return {"error": f"File not found: {filepath}"}
|
|
|
|
content = path.read_text()
|
|
words = content.split()
|
|
lines = content.splitlines()
|
|
|
|
return {
|
|
"file": str(path),
|
|
"bytes": path.stat().st_size,
|
|
"lines": len(lines),
|
|
"words": len(words),
|
|
"characters": len(content)
|
|
}
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print(json.dumps({"error": "Usage: wordcount.py <file>"}))
|
|
sys.exit(1)
|
|
|
|
result = word_count(sys.argv[1])
|
|
print(json.dumps(result, indent=2)) |