Friday, 10 January 2025

Day 85: Python Program to Count the Occurrences of Each Word in a String

 


def count_word_occurrences(input_string):

    words = input_string.split()

    word_count = {}

    for word in words:

        word = word.lower()

        if word in word_count:

            word_count[word] += 1

        else:

            word_count[word] = 1

    return word_count

input_string = input("Enter a string: ")

result = count_word_occurrences(input_string)

print("\nWord occurrences:")

for word, count in result.items():

    print(f"{word}: {count}")

#source code --> clcoding.com 


Code Explanation:

1. Function Definition
def count_word_occurrences(input_string):
The function count_word_occurrences is defined to perform the task of counting words.
It takes one parameter, input_string, which is the string where word occurrences are counted.

2. Splitting the String into Words
words = input_string.split()
The input string is split into a list of words using the split() method.
By default, this splits the string at spaces and removes extra spaces.

3. Initializing an Empty Dictionary
word_count = {}
A dictionary word_count is initialized to store words as keys and their counts as values.

4. Iterating Over Words
for word in words:
    word = word.lower()
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1
The loop iterates through each word in the list words.

Step-by-step:
Convert to Lowercase:
word = word.lower()
This ensures the count is case-insensitive (e.g., "Hello" and "hello" are treated as the same word).

Check if Word is in Dictionary:
If the word already exists as a key in word_count, increment its count by 1:

word_count[word] += 1
If the word is not in the dictionary, add it with an initial count of 1:
word_count[word] = 1

After the loop:
word_count = {"hello": 2, "world!": 1}

5. Returning the Result
return word_count
The dictionary word_count is returned, containing each word as a key and its count as the value.

6. Getting User Input
input_string = input("Enter a string: ")
The program prompts the user to enter a string. The input is stored in input_string.

7. Calling the Function and Displaying Results
result = count_word_occurrences(input_string)

print("\nWord occurrences:")
for word, count in result.items():
    print(f"{word}: {count}")
The count_word_occurrences function is called with the user’s input, and the result is stored in result.
The program iterates through the dictionary result and prints each word along with its count.


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (82) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (179) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (953) Python Coding Challenge (398) Python Quiz (53) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses