#Question 4: Def in
#Question 4: Def in
#Question 4: Def in
Code:
#Question 4
hist={}
length=[]
wordlist=[]
def histogram():
f=open('file.txt','r')
for line in f:
line=line.strip()
line=line.lower()
words=line.split()
for word in words:
if word.isalpha():
if word in hist:
hist[word]=hist[word]+1
else:
hist[word]=1
print("Histogram created!")
f.close()
print("-----Part (a)-----")
histogram()
val=hist.values()
print("Total no of words:",sum(val))
print("No of different words:",len(hist))
Keymax = max(hist, key= lambda x: hist[x])
print("Most common word is:",Keymax)
#b)
def lenword():
f=open('file.txt','r')
for line in f:
line=line.strip()
line=line.lower()
words=line.split()
for word in words:
length.append(len(word))
wordlist.append(word)
f.close()
global freq
freq=dict(zip(wordlist,length))
print("Dictionary successfully created!")
print(freq)
def find_longest_word():
temp=freq.copy()
z=int(input("\nEnter no of longest words to be displayed:"))
for i in range(z):
lenmax = max(temp, key= lambda x: temp[x])
print("The longest words are:",lenmax)
del temp[lenmax]
def filter_long_words(b):
longest=[]
temp=freq.copy()
for j in range(len(freq)):
longwords = max(temp, key= lambda x: temp[x])
del temp[longwords]
if len(longwords)>b:
longest.append(longwords)
else:
break
print("\nThe words longer than",b,"letters are:",longest)
print("\n-----Part (b)-----")
lenword()
find_longest_word()
filter_long_words(7)
Output: