spark: add file_analyzer.py - text file statistics utility
This commit is contained in:
1 parent
223f46085b
commit
59d88693e7
1 file changed
+45
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Text file analyzer - counts lines, words, characters, bytes.
|
||||
Usage: python3 file_analyzer.py <filepath>
|
||||
Outputs JSON to stdout."""
|
||||
|
||||
import sys
|
||||
import json
|
||||
import os
|
||||
|
||||
def analyze_file(filepath):
|
||||
"""Analyze a text file and return stats."""
|
||||
if not os.path.exists(filepath):
|
||||
return {"error": f"File not found: {filepath}"}
|
||||
|
||||
if not os.path.isfile(filepath):
|
||||
return {"error": f"Not a file: {filepath}"}
|
||||
|
||||
stats = {
|
||||
"path": os.path.abspath(filepath),
|
||||
"size_bytes": os.path.getsize(filepath),
|
||||
}
|
||||
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
except Exception as e:
|
||||
return {"error": f"Cannot read file: {e}"}
|
||||
|
||||
stats["size_chars"] = len(content)
|
||||
stats["lines"] = content.count('\n') + (1 if content and not content.endswith('\n') else 0)
|
||||
stats["words"] = len(content.split())
|
||||
stats["unique_chars"] = len(set(content))
|
||||
|
||||
return stats
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print(json.dumps({"error": "Usage: file_analyzer.py <filepath>"}))
|
||||
sys.exit(1)
|
||||
|
||||
result = analyze_file(sys.argv[1])
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
if "error" in result:
|
||||
sys.exit(1)
|
||||
Reference in new issue
Block a user