University of Petroleum and Energy Studies, Dehradun
SANTHOSH C Programming in Petroleum Engineering
SAP ID: 590016364 Assignment - 02
M. Tech Petroleum Engineering Due on 06/09/2024
I year (2024-26)
#Question 1: Write a python program to count the number of frequency of words
occurring in a sentence.
#Sentence "Enter here"
#The data has to be stored in a dictionary named my_dictionary that has the
word as key and frequency as value
#using count method
sentence = "don't trouble the trouble if you trouble the trouble the trouble
troubles you i am not the trouble i am the truth"
lst = []
lst = sentence.split() #keys
freq = [lst.count(i) for i in lst] #values
my_dictionary = dict(zip(lst,freq))
#append keys and values to dictionary
print(my_dictionary)
#Output
{"don't": 1, 'trouble': 6, 'the': 5, 'if': 1, 'you': 2, 'troubles': 1, 'i': 2, 'am': 2, 'not': 1,
'truth': 1}
#without using count method
def frequency_counter(sentence):
#defining a function
dictionary = {}
#create an empty dictionary to store the keys (words) and values (frequencies)
words = sentence.split()
#split the sentence into separate words
for i in words:
if i in dictionary:
dictionary[i] += 1
#count the occurrence of the each word
else:
dictionary[i] = 1
#add the word to the dictionary with count 1
return dictionary
sentence = "don't trouble the trouble if you trouble the trouble the trouble
troubles you i am not the trouble i am the truth"
my_dictionary = frequency_counter(sentence)
print(my_dictionary)
#Output
{"don't": 1, 'trouble': 6, 'the': 5, 'if': 1, 'you': 2, 'troubles': 1, 'i': 2, 'am': 2, 'not': 1,
'truth': 1}