51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Word Frequency Counter - counts words in a file and outputs JSON report.
|
|
Verifiable: deterministic output for given input.
|
|
"""
|
|
import json
|
|
import sys
|
|
from collections import Counter
|
|
from pathlib import Path
|
|
|
|
|
|
def count_words(text: str) -> dict:
|
|
"""Count word frequencies in text."""
|
|
words = text.lower().split()
|
|
return dict(Counter(words))
|
|
|
|
|
|
def process_file(input_path: str, output_path: str = None) -> dict:
|
|
"""Process a file and return word frequency counts."""
|
|
path = Path(input_path)
|
|
if not path.exists():
|
|
raise FileNotFoundError(f"Input file not found: {input_path}")
|
|
|
|
content = path.read_text()
|
|
counts = count_words(content)
|
|
|
|
result = {
|
|
"file": str(path),
|
|
"total_words": sum(counts.values()),
|
|
"unique_words": len(counts),
|
|
"word_counts": counts
|
|
}
|
|
|
|
if output_path:
|
|
Path(output_path).write_text(json.dumps(result, indent=2))
|
|
|
|
return result
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: wordfreq_counter.py <input_file> [output_file]", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
output = process_file(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
|
|
print(json.dumps(output, indent=2))
|
|
return output
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |