Friday, 24 January 2025

Day 100: Python Program to Count the Frequency of Each Word in a String using Dictionary

def count_word_frequency(input_string):

    """

    Counts the frequency of each word in the input string.


    Args:

        input_string (str): The input string.


    Returns:

        dict: A dictionary with words as keys and their frequencies as values.

    """

    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: ")

word_frequency = count_word_frequency(input_string)

print("\nWord Frequency:")

for word, count in word_frequency.items():

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

#source code --> clcoding.com 

 Code explanation:

Function Definition
def count_word_frequency(input_string):
Purpose: This defines a function named count_word_frequency that accepts one parameter, input_string. The function calculates how many times each word appears in the given string.

Docstring
    """
    Counts the frequency of each word in the input string.

    Args:
        input_string (str): The input string.

    Returns:
        dict: A dictionary with words as keys and their frequencies as values.
    """
Purpose: Provides documentation for the function. It explains:
What the function does: It counts the frequency of words in the string.
Arguments: input_string, the string input.
Return Value: A dictionary where each word is a key, and its value is the word’s frequency.

Splitting the String
    words = input_string.split()
What it does:
The split() method divides the string into words, using spaces as the default separator.
Example: "Hello world!" becomes ['Hello', 'world!'].

Initialize the Dictionary
    word_count = {}
What it does: Creates an empty dictionary word_count to store each word as a key and its frequency as the corresponding value.

Loop Through Words
    for word in words:
What it does: Iterates through the list of words obtained from the split() method.

Normalize the Word
        word = word.lower()
What it does: Converts the current word to lowercase to handle case insensitivity.
Example: "Word" and "word" are treated as the same.

Update Word Count in Dictionary
Check if Word Exists
        if word in word_count:
            word_count[word] += 1
What it does:
Checks if the word is already present in the dictionary word_count.
If it is, increments its frequency by 1.

Add Word to Dictionary
        else:
            word_count[word] = 1
What it does:
If the word is not already in the dictionary, adds it as a new key and sets its frequency to 1.

Return the Dictionary
    return word_count
What it does: Returns the word_count dictionary containing the word frequencies.

User Input
input_string = input("Enter a string: ")
What it does: Prompts the user to input a string and stores it in the variable input_string.

Call the Function
word_frequency = count_word_frequency(input_string)
What it does: Calls the count_word_frequency function, passing the user's input string, and stores the resulting dictionary in the word_frequency variable.

Display the Results
print("\nWord Frequency:")
What it does: Prints a header Word Frequency: to label the output.

Loop Through Dictionary
for word, count in word_frequency.items():
    print(f"'{word}': {count}")
What it does:
Iterates through the word_frequency dictionary using the items() method, which returns key-value pairs (word and frequency).
Prints each word and its frequency in the format '{word}': {count}.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (96) AI (38) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (186) C (77) C# (12) C++ (83) Course (67) Coursera (236) Cybersecurity (25) Data Analytics (2) data management (11) Data Science (138) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Euron (22) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (6) 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 (67) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (971) Python Coding Challenge (421) Python Quiz (63) 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