I have a piece of assessment that requires me to swap words within a list. I have given a txt file that contains a column of words that are the 'old words' and a column of word that are the 'new words'. I am required to define a function that check the string to see if a word from the 'old words' list/column is in the string, then I need to swap that word with the corresponding word in the 'new words' column.
For example:
First row, of the two columns of words: ['We, 'You'].
String: "We went to a wedding with our cat" Output: 'You went to a wedding with your cat'
The txt file given contained two columns, and so after writing a bit of code, I managed to split up the words into certain lists, there is a list called 'old_word_list' which contains individual strings of all the words that will/can be in the string, and a list called 'new_word_list' which contains the words that are used to replace the old words.
Pseudo code concept: If string contains any word/s from old_word_list, replace word/s with the words from new_word_list at the same(corresponding) index.
This is the only part of the assessment I am stuck with if someone could kindly help me that would be GREATLY appreciated, also, comment if i have left out any require information. Thank you.
Full code:
# Declaring a global variables for the file, so it can be used in the code.
filename = "reflection.txt"
the_file = open(filename)
# Declaring any other reqiured variables.
word_list = []
old_word_list = []
new_word_list = []
# Creating loop to add all words to a list.
for line in the_file:
# Appends each line to the end of the list declared above. In appending
# the lines, the code also removes the last character on each line (/n).
word_list.append(line[:-1])
# Creating a loop to split each individual word, then appends the
# old/original words to a declared list, and appends the new words
# to a declared list.
for index in range(len(word_list)):
temp_word = word_list[index]
split_words = temp_word.split()
old_word_list.append(split_words[0])
new_word_list.append(split_words[1])
# Defining a function to produce altered statement.
def reflect_statement(statement):
# Swaps the old word with the new word.
for i in range(len(old_word_list)):
if old_word_list[i] in statement:
statement.replace(old_word_list[i], new_word_list[i])
# Replaces '.' and '!' with '?'
for index in range(list_length):
if old_word_list[index] in statement:
statment = statement.replace(old_word_list[index], \
new_word_list[index])
statement = statement.replace(".", "?")
statement = statement.replace("!", "?")
# Returns result statement.
return statement.