Python Question Write a function named uniqueWords that coun
Python Question:
Write a function named uniqueWords that counts how many different words there are in each line of an input file and writes that count to a corresponding line of an output file. The input file already exists when uniqueWords is called. uniqueWords creates the output file.
Input. The function uniqueWords takes two parameters:
inFile, a string that is the name of a text file that is to be read. The file that inFile refers to contains only lower case letters and white space (no punctuation marks or other special characters). outFile, a string that is the name of the file to which uniqueWords writes its output.
The input file is in the current working directory. uniqueWords should create the output file in that directory.
Output. For each line of inFile, uniqueWords should write a corresponding line to outFile containing a single integer: the number of unique words on the line.
If the content of the file turn.txt is below
a time to build up a time to break down
a time to dance a time to mourn
a time to cast away stones a time to gather stones together
the function call
uniqueWords(\'turn.txt\', \'turnOut.txt\')
should create a file named turnOut.txt with this content:
7
5
8
Solution
//Tested on ubuntu,Linux with python 2.7.12
//Code identation should be correct while copying code
/*************program*************/
#/usr/bin/env python
#uniqueWords function is used to find the unique word in a line
#@param input file and output file
#we are splitting line with space and the we used set data structure
#to get unique word
#write the total count into output file_input
# input file must be created before program run
def uniqueWords(file_input,file_output):
for line in file_input:
words=line.split(\" \")
uniqueWords=set(words)
total=len(uniqueWords)
file_output.write(str(total)+\"\ \")
#file input
file_input=open(\"input.txt\",\"r\")
#file output
file_output=open(\"output.txt\",\"w\")
#calling uniqueWords function
uniqueWords(file_input,file_output)
/************output file content***********/
7
5
8
/*********input file content***************/
a time to build up a time to break down
a time to dance a time to mourn
a time to cast away stones a time to gather stones together
Thanks a lot
If you have any query feel free to ask

