In: Computer Science
Design and write a python program that reads a file of text and stores each unique word in some node of binary search tree while maintaining a count of the number appearance of that word. The word is stored only one time; if it appears more than once, the count is increased. The program then prints out 1) the number of distinct words stored un the tree, Function name: nword 2) the longest word in the input, function name: longest 3) the most frequent word in the input, function name: mostfreq 4) the first 10 words appearing in reverse sorted order : first10
In all three format Preorder Postorder Inorder
Answer : Given data
* The word is stored only one time; if it appears more than once, the count is increased.
def nword(txt):
word_list=txt.split() #splitting text into an list of words
unique_words = set(word_list) #Converting List into set [Set remove Duplicates]
result=[]
for word in unique_words:
if word_list.count(word)==1: #checking count of each word in text is 1 or not
result.append(word) # Storing them in a list named result
return result
def longest(txt):
word_list=txt.split() #splitting text into an list of words
sorted_list = sorted(word_list, key=len) # Sorting List Using length
return sorted_list[-1] #return longest word usually appears at last of list accessed by [-1]
def mostfreq(txt):
word_list=txt.split() #splitting text into an list of words
unique_words = set(word_list) #Converting List into set [Set remove Duplicates]
maxfreq=1
mostfreq='unknown'
for word in unique_words:
if word_list.count(word)>maxfreq: #checking count of each word in text is 1 or not
mostfreq=word # Storing most fequent word
maxfreq=word_list.count(word) # updating maximum Frequency
return mostfreq # returning most fequent word
def first10(txt):
word_list=txt.split() #splitting text into an list of words
f10=word_list
if len(word_list)>=11:
f10=word_list[:10] #Splitting list to first 10 words
result=[]
for i in f10:
result.append(i[::-1]) #reversing and storing element in result
result.sort()
return result #Returning Sorted result
f = open("text.txt", "r") #opening a file
txt=f.read() #reading a file
print(nword(txt)) # the number of distinct words stored in the tree
print(longest(txt)) #the longest word in the input, function name
print(mostfreq(txt)) #the most frequent word in the input
print(first10(txt)) #the first 10 words appearing in reverse sorted order