Histogram - String - Word frequency

# Histogram - String - Word Frequency

import operator

string1 = "An algorithm is a step-by-step procedure to solve a given problem. It is a well-defined computational procedure that takes some values as input, manipulates them using a set of instructions and produces some values as output and terminates in a finite amount of time. An algorithm, when formally written in a programming language is called a program, or code. Derivation of an algorithm that solves the problem and conversion of the algorithm into code, together,  is known as Algorithmic Problem Solving."
string1 = string1.lower()

string1 = string1.replace(".", "")
string1 = string1.replace(",", "")
string1 = string1.replace("-", " ")

List1 = string1.split(" ")

dict1 = {}
for ele in List1:
    if ele in dict1:
        dict1[ele] += 1
    else:
        dict1[ele] = 1
print("Histogram")
print("Length of dictionary = ", len(dict1))
print(dict1)

List2 = sorted(dict1.items(), key=operator.itemgetter(1), reverse=True)

dict2 = dict(List2[:3])
print("Most frequently used 3 words:")
print(dict2)

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu