;

Python Program to Count Words in a String Using Dictionary


Tutorialsrack 08/05/2020 Python

In this python program, we will learn how to count words in a string and put it into a dictionary. In this program, we will take the string input from the user and count the words and their frequency and put it into a dictionary as key-value pairs. In this program, we are doing this in two ways. The first way is using a python built-in count(), zip(), dict() and split() functions and the second way is using a count() and split() functions.

Here is the source code of the program to count words in a string and put it into a dictionary.

Program 1: Python Program to Count Words in a String using Dictionary Using count(), dist() and zip() function

In this program, we used the split() function to split the string into words and count() is used to count the number of words in a given string and the dict() function is used to create the dictionary and the zip() function is used to make an iterator that aggregates elements from each of the iterables.

Python Program to Count Words in a String using Dictionary Using count(), dist() and zip() function
# Python Program to Count Words in a String using Dictionary
# Using count(), dist() and zip() function

# Take the input from the user
string = input("Enter any String: ")
words = []

# To Avoid Case-sensitiveness of the string
words = string.lower().split()

frequency = [words.count(i) for i in words]

myDict = dict(zip(words, frequency))
print("Dictionary Items :  ",  myDict)
Output

Enter any String: The first second was alright, but the second second was tough.

Dictionary Items :   {'the': 2, 'first': 1, 'second': 3, 'was': 2, 'alright,': 1, 'but': 1, 'tough.': 1}

Program 2: Python Program to Count Words in a String using Dictionary Using For Loop and count() Function

In this program, we used the split() function to split the string into word list and use a for loop for iterating the words list and the count() function used to count the frequency of the words in a list.

Python Program to Count Words in a String using Dictionary Using For Loop and count() Function
# Python Program to Count Words in a String using Dictionary
# Using For Loop and count() Function

# Take the Input from the User
string = input("Enter any String: ")
words = []

# To Avoid Case-sensitiveness of the string
words = string.lower().split()
myDict = {}
for key in words:
    myDict[key] = words.count(key)

# Print the Input
print("Dictionary Items:  ",  myDict)
Output

Enter any String: The first second was alright, but the second second was tough.

Dictionary Items:   {'the': 2, 'first': 1, 'second': 3, 'was': 2, 'alright,': 1, 'but': 1, 'tough.': 1}


Related Posts



Comments

Recent Posts
Tags