1

Assuming I have this entry in a dictionary:

'Michaele Frendu': ['Micheli Frendu', 'Michael', 'Michaele']

which means that for every instance of the value in the list, it has to be replaced by the key.

ie:

if I have this sample input:

s = 'concessit et assignavit Micheli Frendu presenti viridarium'

this would be replaced by:

s = 'concessit et assignavit Michaele Frendu presenti viridarium'

The problem is when I already have a Michaele Frendu in my text and Michaele is also an item in the list ex:

s = 'Pro Michaele Frendu contra Lucam Zamit'

This is changing to:

s = 'Pro Michaele Frendu Frendu contra Lucam Zamit'

where my desired output is:

s = 'Pro Michaele Frendu contra Lucam Zamit'

In this case I don't want any replacement as the value is already equal to the key.

I am using this regex pattern but is not working:

my_regex = r"\b(?=\w)" + re.escape(l) + r"\b(?!\w)"
s = re.sub(my_regex, k, s)

where k is the key and l is a value from the list

1
  • What about a mere postprocess like .replace('Frendu Frendu', 'Frendu')? How do you build the pattern and run replacements? Can you modify the dictionary values? Commented Oct 12, 2018 at 10:09

1 Answer 1

1

You can simply place the replacement in the first of your regex alternation list, so that it will replace the replacement with itself, with higher precedence than the alternative keywords:

import re
d = {'Michaele Frendu': ['Micheli Frendu', 'Michael', 'Michaele']}
s = 'Pro Michaele Frendu contra Lucam Zamit'
for k, v in d.items():
    print(re.sub('|'.join(map(re.escape, (k, *v))), k, s))

This outputs:

Pro Michaele Frendu contra Lucam Zamit

And with s = 'concessit et assignavit Micheli Frendu presenti viridarium', this outputs:

concessit et assignavit Michaele Frendu presenti viridarium

For clarity, note that '|'.join(map(re.escape, (k, *v))) returns the following during the iteration:

Michaele\ Frendu|Micheli\ Frendu|Michael|Michaele
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.