spark: add text_stats.py - JSON utility to count lines, words, chars in files

This commit is contained in:
spark authored and ledger committed 2026-10-30 05:37:09 +00:00
1 parent 8d176e9cfe
commit 06884eff61
1 file changed
+29 -25
+29 -25
View File
@@ -1,34 +1,38 @@
#!/usr/bin/env python3
"""
text_stats.py - Quick utility to count lines, words, and characters in text files.
Usage: python text_stats.py <file1> [file2] ...
"""
import sys
text_stats.py - Quick utility to count lines, words, and characters in a file.
def analyze_text(filepath):
"""Return (lines, words, chars) for a text file."""
try:
with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
lines = content.count('\n') + (1 if content and not content.endswith('\n') else 0)
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 lines, words, chars
except Exception as e:
return None, None, None
def main():
if len(sys.argv) < 2:
print("Usage: python text_stats.py <file1> [file2] ...")
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)
for filepath in sys.argv[1:]:
lines, words, chars = analyze_text(filepath)
if lines is None:
print(f"{filepath}: error reading file")
continue
print(f"{filepath}: {lines} lines, {words} words, {chars} chars")
if __name__ == '__main__':
main()
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)