У меня есть длинная строка, где я хочу заменить десятки выражений регулярных выражений, поэтому я создал словарь, подобный этому:
replacements = { r'\spunt(?!\s*komma)' : r".",
r'punt komma' : r",",
r'(?<!punt )komma' : r",",
"paragraaf" : "\n\n" }
Приведенный выше словарь является небольшим выбором.
Как я могу применить это к документу строк? Пример строки:
text = ""a punt komma is in this case not a komma and thats it punt"
Я пробовал что-то вроде этого:
import re
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)
if __name__ == "__main__":
text = "Larry Wall is the creator of Perl"
dict = {
"Larry Wall" : "Guido van Rossum",
"creator" : "Benevolent Dictator for Life",
"Perl" : "Python",
}
print(multiple_replace(dict, text))
Но это работает только при замене строк, а не в шаблоне регулярных выражений, как мой словарь.