In this homework, you will be writing a short program in Python to find duplicat
ID: 3810595 • Letter: I
Question
In this homework, you will be writing a short program in Python to find duplicate words in a file. This assignment focuses on Chapter 6, specifically reading data from a file. A common mistake when composing a document is duplicating a word ("the the"). This is a big enough problem that Microsoft Word and other text editing software will mark these mistakes as errors. In this assignment, we will develop a short Python program that will find these duplicate words and alert the user by printing out a simple message. I suggest using a for loop to read the file data line by line. Once you have a line you will need to perform further string manipulations to determine if there's a duplicate word. Given the following (slightly mangled) text stored inside of quote. txt: He that would make his own liberty liberty secure, must guard even his enemy from oppression; for for if he violates this duty, he he establishes a precedent that will reach to himself. Thomas Paine Running your program would produce the following output (user input is green): Enter file name: quote.txt Found word: "liberty" on line 1. Found word: "for" on line 3. Found word: "he" on line 4.Explanation / Answer
# link for code in case indentation mess up: https://goo.gl/t2cd5m
filename = raw_input("Enter file name: ")
with open(filename) as fh:
line_no = 0
prev_word = ""
for line in fh:
line_no += 1
words = line.split()
found_word = ""
found = False
for word in words:
if word == prev_word:
found = True
found_word = word
prev_word = word
if found:
print "Found word: "" + found_word + "" on line " + str(line_no) + "."
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.