Replace apostrophe/short words in python

前端 未结 3 506
失恋的感觉
失恋的感觉 2021-01-04 20:26

I am using python to clean a given sentence. Suppose that my sentence is:

What\'s the best way to ensure this?

I want to convert:



        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 20:57

    The answers above will work perfectly well and could be better for ambiguous contraction (although I would argue that there aren't that much of ambiguous cases). I would use something that is more readable and easier to maintain:

    import re
    
    def decontracted(phrase):
        # specific
        phrase = re.sub(r"won\'t", "will not", phrase)
        phrase = re.sub(r"can\'t", "can not", phrase)
    
        # general
        phrase = re.sub(r"n\'t", " not", phrase)
        phrase = re.sub(r"\'re", " are", phrase)
        phrase = re.sub(r"\'s", " is", phrase)
        phrase = re.sub(r"\'d", " would", phrase)
        phrase = re.sub(r"\'ll", " will", phrase)
        phrase = re.sub(r"\'t", " not", phrase)
        phrase = re.sub(r"\'ve", " have", phrase)
        phrase = re.sub(r"\'m", " am", phrase)
        return phrase
    
    
    test = "Hey I'm Yann, how're you and how's it going ? That's interesting: I'd love to hear more about it."
    print(decontracted(test))
    # Hey I am Yann, how are you and how is it going ? That is interesting: I would love to hear more about it.
    

    It might have some flaws I didn't think about though.

提交回复
热议问题