ReAct-Text-Analyzer / src /tools /word_counter.py
Easonwangzk's picture
Initial commit
a01e687
"""Word counting tool."""
import re
from collections import Counter
from typing import Dict, Any
from .base_tool import BaseTool
class WordCounter(BaseTool):
"""Counts words and provides word frequency statistics."""
@property
def description(self) -> str:
return (
"Counts the total number of words, unique words, and provides "
"the top 10 most frequent words in the text. "
"Use this when you need word count or frequency information."
)
def run(self, text: str) -> Dict[str, Any]:
"""Count words in the text.
Args:
text: Input text to analyze
Returns:
Dictionary with word count statistics
"""
# Clean and tokenize text
words = re.findall(r'\b[a-zA-Z]+\b', text.lower())
if not words:
return {
"total_words": 0,
"unique_words": 0,
"top_10_words": []
}
# Count frequencies
word_freq = Counter(words)
return {
"total_words": len(words),
"unique_words": len(word_freq),
"top_10_words": word_freq.most_common(10),
"average_word_length": sum(len(w) for w in words) / len(words)
}