In: Computer Science
In Python. A file concordance tracks the unique words in a file and their frequencies. Write a program that displays a concordance for a file. The program should output the unique words and their frequencies in alphabetical order. Variations are to track sequences of two words and their frequencies, or n words and their frequencies.
Below is an example file along with the program input and output:
Input : test.txt
output : 3/4 1, 98 1, AND 2, GUARANTEED 1, INDEED 1, PERCENT 1, SUCCEED 1, WILL 2, YES 1, YOU 2
The code needs to read different files by name and also the count the amount of times or occurrence the word showed up and attach the number to the word like above.. The text file will say
"AND YOU WILL SUCCEED
YES
YES YOU WILL INDEED
98 AND 3/4 PERCENT"
Test.txt
AND YOU WILL SUCCEED
YES GAURANTEED
YES YOU WILL INDEED
98 AND 3/4 PERCENT
code
file = open("test.txt") #open file
s = file.read().replace("\n"," ") #store file elements in string
file.close() #close the file
l = s.split(" ") # convert into list by removing spaces
l.sort() #sort the list
d={} #dictionary
for i in l:
if i in d:
d[i]=d[i]+1 #if word already in dictionary increase the count
else:
d[i]=1 #if word first time occurs store in dictionary with count 1
for k,v in d.items():
print(k,v,end=",") #print the word and its count
Terminal Work
.