Friday 1 January 2021

Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary

 This is a Python Program to count the frequency of words appearing in a string using a dictionary.

Problem Description

The program takes a string and counts the frequency of words appearing in that string using a dictionary.

Problem Solution

1. Enter a string and store it in a variable.
2. Declare a list variable and initialize it to an empty list.
3. Split the string into words and store it in the list.
4. Count the frequency of each word and store it in another list.
5. Using the zip() function, merge the lists containing the words and the word counts into a dictionary.
3. Print the final dictionary.
4. Exit.

Program/Source Code

Here is source code of the Python Program to count the frequency of words appearing in a string using a dictionary. The program output is also shown below.

test_string=raw_input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Program Explanation

1. User must enter a string and store it in a variable.
2. A list variable is declared and initialized to an empty list.
3. The string is split into words using a space as the reference and stored in the list.
4. The frequency of each word in the list is counted using list comprehension and the count() function.
5. The final dictionary is created using the zip() function and is printed.

Runtime Test Cases
 
Case 1:
Enter string:hello world program world test
{'test': 1, 'world': 2, 'program': 1, 'hello': 1}
 
Case 2:
Enter string:orange banana apple apple orange pineapple
{'orange': 2, 'pineapple': 1, 'banana': 1, 'apple': 2}

No comments:

Post a Comment