Count Characters, Words, and Lines in Python Text
Counts characters, words, lines, and the most common words in a given string using Python's standard library.
Python code
23 linesfrom collections import Counter
def count_data(text):
"""Count characters, words, lines, and most common words in text."""
char_count = len(text)
word_count = len(text.split())
line_count = text.count("\n") + 1
word_freq = Counter(text.lower().split())
most_common = word_freq.most_common(3)
return {
"characters": char_count,
"words": word_count,
"lines": line_count,
"most_common_words": most_common,
}
if __name__ == "__main__":
sample_text = "The quick brown fox jumps over the lazy dog\nThe dog sleeps."
result = count_data(sample_text)
print(result)
Output
{'characters': 52, 'words': 10, 'lines': 2, 'most_common_words': [('the', 3), ('dog', 2), ('quick', 1)]}
How it works
The Counter from the collections module tallies word frequencies efficiently. text.split() splits on whitespace and counts words; text.count("\n") + 1 gives line count, assuming text ends without a newline. The function returns a dictionary with easy-to-read metrics. This pattern is useful for quick text analysis without external dependencies.
Common mistakes
- Forgetting to lower-case text before counting most common words, causing case-sensitive duplicates.
- Counting a trailing newline as an extra line when using `count("\n") + 1` without adjusting for empty lines.
- Assuming `split()` splits on punctuation, but it only splits on whitespace.
Variations
- Use `re.findall(r'\b\w+\b', text.lower())` to count words with regex for better punctuation handling.
- Return a sorted list of all word frequencies instead of only the top 3.
Real-world use cases
- Generating content statistics for a blog post editor to show word count and readability hints.
- Analyzing log files to identify the most frequent error messages for troubleshooting.
- Building a simple text summary tool that reports key metrics before further NLP processing.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Extract Data from Strings in Python: Beginner's Guide easy
- Extract Email-Like Tokens from Text in Python easy
Keep learning
Related tutorials and quizzes for this topic.