Replacing words in string
- by abkai
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.