Answer:
I am writing a Python program.
def concordance(filename): # function that takes a file name as parameter and returns the concordance for that file
file = open(filename,"r") #opens file in read mode
unique={} #creates and empty list
for word in file.read().split(): #loops through every word in the file
if word in unique: # if words is already present in the list
unique[word] += 1 #add 1 to the count of the existing word
else: #if word is not present in the list
unique[word] = 1 #add the word to the list and add 1 to the count of word
file.close(); # close the file
for x in sorted(unique): #sort the list and displays words with frequencies
print(x, unique[x]); #prints the unique words and their frequencies in alphabetical order
#prompts user to enter the name of the file
file_name=input('Enter the input file name: ')
concordance(file_name) #calls concordance method by passing file name to it
Step-by-step explanation:
The program has a function concordance that takes a text file name as parameter and returns a list of unique words and their frequencies.
The program first uses open() method to open the file in read mode. Here "r" represents the mode. Then creates an empty list named unique. Then the for loop iterates through each word in the file. Here the method read() is used to read the contents of file and split() is used to return these contents as a list of strings. The if condition inside the loop body checks each word if it is already present in the list unique. If the word is present then it adds 1 to the count of that word and if the word is not already present then it adds that unique word to the list and assign 1 as a count to that word. close() method then closes the file. The second for loop for x in sorted(unique): is used to display the list of unique words with their frequencies. sorted() method is used to sort the list and then the loop iterates through each word in the list, through x, which acts like an index variable, and the loop displays each word along with its frequency.