Замена текстовых данных с использованием словаря - PullRequest
0 голосов
/ 12 апреля 2019

Рамка данных со структурой ниже -

ID text
0  Language processing in python th is great
1  Relace the string 

Словарь с именем custom fix

{'Relace': 'Replace', 'th' : 'three'}

Попробовал код и вывод поступил как - Токовый выход -

ID text
0  Language processing in pythirdon three is great
1  Replace threee string 

Код:

def multiple_replace(dict, text):
  # Create a regular expression  from the dictionary keys
  regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

  # For each match, look-up corresponding value in dictionary
  return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 

df['col1'] = df.apply(lambda row: multiple_replace(custom_fix, row['text']), axis=1)

Ожидаемый результат -

ID text
0  Language processing in python three is great
1  Replace the string

Ответы [ 2 ]

1 голос
/ 12 апреля 2019

Я не эксперт по регулярным выражениям, и, возможно, это не лучшее решение, но использование границ слов \b в вашем регулярном выражении должно решить проблему, вот фиксированная функция:

def multiple_replace(d, text):
    # Create a regular expression  from the dictionary keys
    regex = re.compile("(%s)" % "|".join(["\\b" + x + "\\b" for x in d.keys()]))

    # For each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: d[mo.string[mo.start():mo.end()]], text)

0 голосов
/ 12 апреля 2019

Вы также можете разбить строку, чтобы получить все слова и перебрать список.

    def multiple_replace(d, text):
        splitText=text.split()
        disc=len(set(splitText).intersection(set(d.keys())))
        if disc==0:    
            return ' '.join(splitText)
        else:
            for k in range(len(splitText)):      
                try:        
                    splitText[k]=d[splitText[k]]        
                except KeyError:        
                    pass
            return ' '.join(splitText)

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...