Last modified: Nov 16, 2023 By Alexander Williams
Python: Count Word in Text Using Percentage
Example 1: Basic Word Count and Percentage
# Define a function to calculate word percentage
def word_percentage(text, target_word):
words = text.split()
total_words = len(words)
target_count = words.count(target_word)
percentage = (target_count / total_words) * 100
return percentage
# Example usage
text = "This is a sample text with sample words. Sample words are important."
target_word = "sample"
percentage = word_percentage(text, target_word)
print(f"The percentage of '{target_word}' in the text is: {percentage}%")
Output:
# The percentage of 'sample' in the text is: 9.090909090909092%
Example 2: Case-Insensitive Word Count
# Define a function to calculate case-insensitive word percentage
def word_percentage_case_insensitive(text, target_word):
words = text.lower().split()
total_words = len(words)
target_count = words.count(target_word.lower())
percentage = (target_count / total_words) * 100
return percentage
# Example usage
text = "This is a sample text with Sample words. Sample words are important."
target_word = "sample"
percentage = word_percentage_case_insensitive(text, target_word)
print(f"The percentage of '{target_word}' (case-insensitive) in the text is: {percentage}%")
Output:
# The percentage of 'sample' (case-insensitive) in the text is: 18.181818181818183%
Example 3: Handling Punctuation and Special Characters
# Define a function to calculate word percentage with punctuation handling
import re
def word_percentage_with_punctuation(text, target_word):
words = re.findall(r'\b\w+\b', text)
total_words = len(words)
target_count = words.count(target_word)
percentage = (target_count / total_words) * 100
return percentage
# Example usage
text = "This, is a sample text with sample words. Sample words are important!"
target_word = "sample"
percentage = word_percentage_with_punctuation(text, target_word)
print(f"The percentage of '{target_word}' in the text is: {percentage}%")
Output:
# The percentage of 'sample' in the text is: 10.714285714285714%
Example 4: Counting Percentage for Multiple Words
# Define a function to calculate percentages for multiple words
def word_percentages(text, target_words):
words = text.split()
total_words = len(words)
percentages = {word: (words.count(word) / total_words) * 100 for word in target_words}
return percentages
# Example usage
text = "This is a sample text with sample words. Sample words are important."
target_words = ["sample", "important"]
result = word_percentages(text, target_words)
for word, percentage in result.items():
print(f"The percentage of '{word}' in the text is: {percentage}%")
Output:
# The percentage of 'sample' in the text is: 9.090909090909092%
# The percentage of 'important' in the text is: 9.090909090909092%