Python Question Question 12 Write a function named repeatCount(). The function r
ID: 3576134 • Letter: P
Question
Python Question
Question 12
Write a function named repeatCount(). The function repeatCount() takes two string parameters: the name of an input file and the name of an output file. The function repeatCount() should read each line of the input file, identify the number of words on the line that occur more than once, and write that number to a line in the output file. A word should be considered to be repeated if occurs with different capitalization. That is, 'To' and 'to' are the same word. You may assume that the file contains only upper and lower case letters and white space; it does not contain any punctuation marks.
For example, suppose the input file contains the following four lines:
Woke up this morning with an ache in my head
I splashed on my clothes as I spilled out of bed
I opened the window to listen to the news
But all I heard was the Establishment Blues
Then the output file should contain the following four lines:
0
1
2
2
0
Question 13
Write a function named wordPositions() with the following input and output.
Input: s, a string consisting of upper and lower case letters and spaces.
Return: a dictionary in which each distinct word in s is a key and the corresponding value is a list of the positions in s in which the word occurs. Words are to be treated as the same regardless of their capitalization. That is, "Yes" and "yes" are the same word.
The following is an example of correct output.
>>> s = 'One fish two fish red fish blue fish'
>>> wp = wordPositions(s)
>>> print(wp)
{'two': [2], 'one': [0], 'red': [4], 'fish': [1, 3, 5, 7], 'blue': [6]}
Explanation / Answer
def repeatCount(inputFile, outputFile):
#open file and read each line
output = open(outputFile, "w+")
with open(inputFile, "r+") as f:
for line in f:
#split the line into words
line = line.rstrip()
words = line.split(" ")
#convert all words in lowercase
words = [x.lower() for x in words]
print(words)
#for every line output the number of words with count greater than one
output.write(str(len(words) - len(list(set(words)))) + ' ')
#save output file and close input file
output.close()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.