mercredi 15 janvier 2020

Changing backslash to if else code in python 3.7

I am trying to understand this code that uses contraction module:

def expand_match(contraction):
    match = contraction.group(0)
    first_char = match[0]
    expanded_contraction = contraction_mapping.get(match)\
                           if contraction_mapping.get(match)\
                           else contraction_mapping.get(match.lower())                       
    expanded_contraction = first_char+expanded_contraction[1:]
    return expanded_contraction

In the error message it says:

<ipython-input-73-3210e198815e> in expand_contractions(text, contraction_mapping)
     10         expanded_contraction = first_char+expanded_contraction[1:]
     11         return expanded_contraction
---> 12     expanded_text = contractions_pattern.sub(expand_match, text)
     13     expanded_text = re.sub("'", "", expanded_text)
     14     return expanded_text

<ipython-input-73-3210e198815e> in expand_match(contraction)
      8                                if contraction_mapping.get(match)\
      9                                else contraction_mapping.get(match.lower())
---> 10         expanded_contraction = first_char+expanded_contraction[1:]
     11         return expanded_contraction
     12     expanded_text = contractions_pattern.sub(expand_match, text)

TypeError: 'NoneType' object is not subscriptable

It seems that expanded_contraction is not returning anything -- is there a way to change the code into a default if-else statement?

Aucun commentaire:

Enregistrer un commentaire