44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Text file analyzer: count words, lines, characters."""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def analyze_file(filepath: str) -> dict:
|
|
"""Analyze a text file and return counts."""
|
|
p = Path(filepath)
|
|
if not p.exists():
|
|
raise FileNotFoundError(f"File not found: {filepath}")
|
|
|
|
content = p.read_text(encoding='utf-8')
|
|
lines = content.splitlines()
|
|
|
|
return {
|
|
'filepath': filepath,
|
|
'lines': len(lines),
|
|
'words': len(content.split()),
|
|
'characters': len(content),
|
|
'bytes': len(content.encode('utf-8'))
|
|
}
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: text_analyzer.py <file>", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
try:
|
|
result = analyze_file(sys.argv[1])
|
|
print(f"File: {result['filepath']}")
|
|
print(f"Lines: {result['lines']}")
|
|
print(f"Words: {result['words']}")
|
|
print(f"Characters: {result['characters']}")
|
|
print(f"Bytes (UTF-8): {result['bytes']}")
|
|
except FileNotFoundError as e:
|
|
print(f"Error: {e}", file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main() |