1. Introduction
Counting the occurrences of each word in a string is a typical task in text analysis. This process is essential in areas such as natural language processing, data analysis, and search engine technology. Python provides simple yet powerful tools to perform such counts efficiently.
2. Program Steps
1. Define the string to analyze.
2. Split the string into words based on whitespace.
3. Use a dictionary to track the count of each word.
4. Iterate over the list of words, incrementing their count in the dictionary.
5. Output the word counts.
3. Code Program
# Define the string
input_string = "This is a test string with some words this is."
# Split the string into words
words = input_string.lower().split()
# Initialize a dictionary to count occurrences
word_count = {}
# Count the occurrences of each word in the string
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# Print the count of each word
print("Word counts:")
for word, count in word_count.items():
print(f"'{word}': {count}")
Output:
Word counts: 'this': 2 'is': 2 'a': 1 'test': 1 'string': 1 'with': 1 'some': 1 'words': 1
Explanation:
1. input_string is the string in which we want to count the occurrences of each word.
2. The split() method is used to break the string into words, after converting input_string to lowercase with lower() for case-insensitive counting.
3. word_count is a dictionary that will hold the count of each word.
4. The for loop iterates through the list words, and for each word, the dictionary word_count is updated.
5. If word is already a key in word_count, its value is incremented; otherwise, it is added to the dictionary with a value of 1.
6. After the loop, word_count contains the counts of each word that appeared in input_string.
7. Another for loop iterates through the word_count dictionary to print the count of each word, formatted in a string using an f-string.
Comments
Post a Comment
Leave Comment