0

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.
1
  • -1 for absence of code sample Commented Apr 11, 2012 at 11:46

5 Answers 5

3

You can use this code:

# the words to be replaced
old_word_list=['We','cat']

# the new words
new_word_list=['You','dog']

my_string="We went to a wedding with our cat"

# it prints "We went to a wedding with our cat"
print my_string

# iterate over the list of old words
for word in old_word_list:
  # get the index of the current word
  index = old_word_list.index(word)

  # use this index to do the replacement with the words of the two lists
  my_string = my_string.replace(old_word_list[index], new_word_list[index])

# it prints "You went to a wedding with our dog"
print my_string

Updated answer according to author's comments:

# the words to be replaced
old_word_list=['We','cat']

# the new words
new_word_list=['You','dog']

def reflect_statement(statement):
  # iterate over the list of old words
  for word in old_word_list:
    # get the index of the current word
    index = old_word_list.index(word)

    # use this index to do the replacement with the words of the two lists
    statement = statement.replace(old_word_list[index], new_word_list[index])

  return statement

mystring="We went to a wedding with our cat"
mystring = reflect_statement(mystring)
print mystring

Updated answer after last added source code by author:

change your function to this one:

def reflect_statement(statement, old_word_list, new_word_list):
  mystr=statement
  # iterate over the list of old words
  for word in old_word_list:
    # get the index of the current word
    index = old_word_list.index(word)

    # use this index to do the replacement with the words of the two lists
    mystr = mystr.replace(old_word_list[index], new_word_list[index])

  return mystr
Sign up to request clarification or add additional context in comments.

13 Comments

This is SO CLOSE! i think... Since this code needs to be in a function, because it uses test cases, i have altered (possibly incorrectly) your code so that it should work. I have deleted the first four lines of your code as it is not needed. And i have change where you see 'my_string' to 'statement' Because my function is 'def reflect_statement(statement):' I get this error: statement = statement.replace(old_word_list[index], new_word_list[index]) IndexError: list index out of range Any ideas? Thanks
probably the tow lists you use for the mapping are not of the same length.. Make sure that old_word_list and new_word_list have the same number of elements (Strings).
Ok. I got it to NOT give me an error, although this time, it just doesn't work, they dont swap. Ideas?
They do have the same number of elements in them.
ok, maybe you have to initialize my_string variable with the statement argument, that is my_string=statement before the loop. Then you have to return my_string. store the result of the function call to a variable and print it: res=reflect_statement(statement) and then print res. I cannot imagine something else, maybe it is better to see your code..
|
1

Hints:

  1. "string string".split() # Split a string on whitespace into a list
  2. You can use a for loop to loop over a list
  3. lists have a myList.index(element) to tell you if an element is in the list and return its index.
  4. The indexes will match between your two lists (according to your description)
  5. strings also have a "myString.replace(old, new)" method in case you want to go that route.

Comments

0
# map old to new words (assuming there are no duplicates)
replacement_mapping = dict(zip(old_word_list, new_word_list))

# go through each word of the string, if it's in the mapping, use replacement, otherwise the word from the string
new_string = ' '.join([replacement_mapping.get(word, word) for word in given_string.split(' ')])

3 Comments

1) Note this is a homework question; 2) This has got to be too advanced for what he is doing I am sure of it.
As @jdi said. I think this is too advanced for what i am doing. As i am a year 12 student doing an early start at a university for a basic first year subject. So i do thank you for your input, and although this probably works when incorporated properly, i cannot quite understand it. Thanks
Right, I missed the homework tag... So good luck! I hope this will not stay a mystery for you for very long.
0

I'm going to state some assumptions I've made before posting my answer so please correct me if any of these are wrong.

Assumption 1: there are the same number of words in each column Assumption 2: there is one, and only one 'partner' for each word, making one word pair

That being the case, I would make each word pair a list in its own right. Then, to continue your psuedo-code, for each line of text, check each word pair and replace word[0] with word[1].

EDIT Sorry just spotted I've worded this ambiguously. When making the word-pair lists I would store these in a list too, for example [["old1", "new1"], ["old2", "new2"]] then run your loops to replace them (I'm not giving example code just now because I'm conscious you're doing an assignment so probably want to solve the problem, but let me know if you're struggling).

3 Comments

Both those assumptions are correct, sorry for not stating them. And your pseudo-code does make perfect sense. Now i just need to see if i can write the actual code XD
I thank you for your help. I am not even in my first year of uni, i am doing an early start for uni where i do only one first year subject. So bare with me :) I do not really know how to write the code that puts them into pair lists. See the EDIT i made to the question, at the bottom is the code that splits up the strings to that there is a list for the old words and a list for the new. I know i need to edit this to make the pair list but i do not know how? Thank you!
I successfully formatted the strings like this: [["old1", "new1"], ["old2", "new2"]] But i am not sure how to do the replace part, as nothing i try works.
0

if i'm understanding you right, this may be it, but it's not pretty:

for i in range( len(old_word_list) )
    if old_word_list[i] in "some string":
         "some string".replace(old_word_list[i], new_word_list[i])

4 Comments

This looks close to what i need, although when i put it in my function, it does not work, it doesn't give an error, it just doesn't swap the words. This is what the code looks like: def reflect_statement(statement): for index in range(len(old_word_list)): if old_word_list[index] in statement: old_word_list[index] = new_word_list[index]
if one of the elements in old_word_list[i] is not a string you may need: if str( old_word_list[i] ) in "some string": But if you don't get an error, i assume non of the elements of the list match the string (case not the same?)
There are no repeats in any of the strings for the whole text file. And since there are test cases it shows me that 0 passed out of 18. So sadly it just does not work, i have no idea.
Ok. So since this uses testcases, and i need to create a function. All i changed of your code is, "some string" is now change to statement (this is the function parameter). And it is still not swapping them. To be honest, i think you code works although there might be some other code i wrote somewhere that doesnt make it work. But i have no clue what or where. I will post my full code in the question as an EDIT at the bottom. So you can see if im doing something wrong. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.