38 lines
1.0 KiB
Python
38 lines
1.0 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
text_stats.py - Quick utility to count lines, words, and characters in a file.
|
|
|
|
Usage: python3 text_stats.py <file_path>
|
|
Output: JSON with {path, lines, words, chars}
|
|
"""
|
|
|
|
import sys
|
|
import json
|
|
from pathlib import Path
|
|
|
|
|
|
def text_stats(path: str) -> dict:
|
|
"""Return dict with lines, words, and chars count for given file."""
|
|
p = Path(path)
|
|
if not p.is_file():
|
|
raise FileNotFoundError(f"No such file: {path}")
|
|
|
|
content = p.read_text()
|
|
lines = len(content.splitlines()) if content.strip() else 0
|
|
words = len(content.split())
|
|
chars = len(content)
|
|
|
|
return {"path": str(p.resolve()), "lines": lines, "words": words, "chars": chars}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 2:
|
|
print(json.dumps({"error": "Usage: text_stats.py <file_path>"}))
|
|
sys.exit(1)
|
|
|
|
try:
|
|
result = text_stats(sys.argv[1])
|
|
print(json.dumps(result, indent=2))
|
|
except Exception as e:
|
|
print(json.dumps({"error": str(e)}))
|
|
sys.exit(1) |