Zamiana wystąpień wyrażeniem regularnym ze słownika

0

Hej mam string

s = r'This is a first \thing to replace and this is a second \thing2 to replace'

i dictionary z wartosci ktore chce wstawic:

things = {
    r'\thing': "REPLACED1",
    r'\thing2': "REPLACED2"
}

Czyli \thing chce zastapic przez REPLACED1 itp ale to nie dziala:

for thing, value in things.items():
    s = re.sub(r'\b' + thing + r'\b', value, s)

Wie ktos moze co powinienem poprawic?

49

Pewnie nie działa Ci bo \ to escape sign. Dawno nie bawiłem się regexem i już nie pamiętam z głowy jak go sparsować na stringa. Za pewne 3 min szukania w google ;)

5

Masz wzorzec:

r'\thing': "REPLACED1",

a powinno to wyglądać tak:

r'\\thing': "REPLACED1",

Druga sprawa to \b. On łapie granice dla znaków które łapie \w.
Więc jak masz znak lewego ukośnika , to twój wzorzec nie będzie pasował.
Dokumentacja:
https://docs.python.org/3/library/re.html
Przeczytaj o znaczniku \b.

2

Jak piszą powyżej, poczytaj o, \b, bo nie możesz tego użyć w ten sposób. Moze zamiast, \b wyodrębnić ograniczenia? Np., dla spacji:
s1 = re.sub(r"[\s]+\\thing[\s]+", " REPLACED ", s)

1

Żeby to był poprawny regexp, to musisz to napisać tak:

from re import escape

s = r'This is a first \thing to replace and this is a second \thing2 to replace, thing\thing'

things = {
    r'\thing': "REPLACED1",
    r'\thing2': "REPLACED2"
}

for thing, value in things.items():
    s = re.sub(r'\b' + escape(thing) + r'\b', value, s)

Teraz pojawia się pytanie, co się ma stać, jeśli dam np taki string: s = r'This is \thing and thing\thing'? Czy ma zostać zamienione na r'This is REPLACED1 and thingREPLACED1'? Czy ma zostać s = r'This is REPLACED1 and thing\thing'? Oraz czy ma podmienić \things?

Jeśli to pierwsze, to jesteś w domu. Jeśli to drugie, to musisz zamienić pierwsze \b, tak że:

import re
from re import escape

s = r'This is a first \thing to replace and this is a second \thing2 to replace, thing\thing also \things'

things = {
    r'\thing': "REPLACED1",
    r'\thing2': "REPLACED2"
}

for thing, value in things.items():
    s = re.sub(r'(?<=\s)' + escape(thing) + r'(?=\s)', value, s)
    

Pojawia się też pytanie czy powinno podmienić np (\thing), ale to chyba temat na inną rozmowę.

1 użytkowników online, w tym zalogowanych: 0, gości: 1