Search code examples
pythonstringsingle-quotes

it's instead of it's in python string


My python string consists of ' instead of ' (single quotes). My current objective is to expand compound words like It's to It is, Haven't to Have not.

"This has been great for me. I've been on it for 2 weeks and in the last week I only had 3 headaches which went away with 2 Tylenol. I was having chronic daily headaches that wouldn't go away no matter what I took. I'm still a little sleepy during the day, but I know that will get better."

The above statement is an example of the sentence I've been trying to convert.

Can someone suggest a way to convert this into the string format?


Solution

  • text = "This has been great for me. I've been on it for 2 weeks and in the last week I only had 3 headaches which went away with 2 Tylenol. I was having chronic daily headaches that wouldn't go away no matter what I took. I'm still a little sleepy during the day, but I know that will get better."
    d_contraction = {"I'm":"I am","wouldn't":"would not","I've":"I have"}
    updated_text = text.replace(''', "'") 
    print(updated_text)
    for k,v in d_contraction.items():
        updated_text = updated_text.replace(k,v) 
    print(updated_text)
    

    Output:

    This has been great for me. I've been on it for 2 weeks and in the last week I only had 3 headaches which went away with 2 Tylenol. I was having chronic daily headaches that wouldn't go away no matter what I took. I'm still a little sleepy during the day, but I know that will get better.
    
    This has been great for me. I have been on it for 2 weeks and in the last week I only had 3 headaches which went away with 2 Tylenol. I was having chronic daily headaches that would not go away no matter what I took. I am still a little sleepy during the day, but I know that will get better.
    

    The above code will work for the text you have provided. Basically, you will have to create a dictionary of all the possible contractions examples - they'll, ther're, etc.