Replacing words in string

Posted by abkai on Stack Overflow See other posts from Stack Overflow or by abkai
Published on 2012-12-16T10:51:01Z Indexed on 2012/12/16 11:04 UTC
Read the original article Hit count: 217

Filed under:
|
|
|
|

Okay, so I have the following little function:

def swap(inp):
    inp = inp.split()
    out = ""

    for item in inp:
        ind  = inp.index(item)
        item = item.replace("i am",    "you are")
        item = item.replace("you are", "I am")
        item = item.replace("i'm",     "you're")
        item = item.replace("you're",  "I'm")
        item = item.replace("my",      "your")
        item = item.replace("your",    "my")
        item = item.replace("you",     "I")
        item = item.replace("my",      "your")
        item = item.replace("i",       "you")
        inp[ind] = item

    for item in inp:
        ind  = inp.index(item)
        item = item + " "
        inp[ind] = item

    return out.join(inp)

Which, while it's not particularly efficient gets the job done for shorter sentences. Basically, all it does is swaps pronoun etc. perspectives. This is fine when I throw a string like "I love you" at it, it returns "you love me" but when I throw something like:

you love your version of my couch because I love you, and you're a couch-lover.

I get:

I love your versyouon of your couch because I love I, and I'm a couch-lover. 

I'm confused as to why this is happening. I explicitly split the string into a list to avoid this. Why would it be able to detect it as being a part of a list item, rather than just an exact match?

Also, slightly deviating to avoid having to post another question so similar; if a solution to this breaks this function, what will happen to commas, full stops, other punctuation?

It made some very surprising mistakes. My expected output is:

I love my version of your couch because you love I, and I'm a couch-lover.

The reason I formatted it like this, is because I eventually hope to be able to replace the item.replace(x, y) variables with words in a database.

© Stack Overflow or respective owner

Related posts about python

Related posts about list