import re
input_text = "Ellos son grandes amigos, pronto ellos se convirtieron en mejores amigos. ellos se vieron en el parque antes de llevar ((PERS)los viejos gabinetes), ya que ellos eran aun útiles para la compañía. Ellos son algo peores que los nuevos modelos."
output_text = re.sub(r"(?<!\(\(PERS\)\s*los\s*)ellos", r"((PERS)ellos NO DATA)", input_text, flags=re.IGNORECASE)
print(repr(output_text)) # --> output
I must replace any remaining occurrence of the substring "ellos"
within the input string by ((PERS)ellos NO DATA)
, that is, it will be replaced in those cases where there is no sequence ((PERS)\s*los )
before
And to the string that the program received as input, it should be able to convert it into this other string:
"((PERS)ellos NO DATA) son grandes amigos, pronto ((PERS)ellos NO DATA) se convirtieron en mejores amigos. ((PERS)ellos NO DATA) se vieron en el parque antes de llevar ((PERS)los viejos gabinetes), ya que ellos eran aun útiles para la compañía. Ellos son algo peores que los nuevos modelos."
But the problem is that this code when using look-arounds indicates this error re.error: look-behind requires fixed-width pattern
How does this error happen since Python's regex engine requires fixed-width look-behind patterns, the length of the regex in the lookbehind must be a fixed number of characters, but since I use *
no longer I am fulfilling that condition, and this error appears. What alternative could I use in this case to avoid this error, and obtain the correct result?
And if I use this pattern instead
re.sub(r"ellos(?!((?<=\()\(PERS\)los ))", r"((PERS)ellos NO DATA)", input_text, flags=re.IGNORECASE)
will replace absolutely all occurrences of the string "ellos"
regardless of the restriction that it should replace only when there is no ((PERS) )
before it
getting this wrong output:
'Creo que ((PERS)los viejos gabinetes) estan en desuso, hay que hacer algo con ellos, ya que ellos son importantes. ((PERS)viejos gabinetes) quedaron en el deposito de ((PERS)viejos gabinetes). ((PERS)viejos gabinetes) ((PERS)los cojines) son acolchonados, ellos estan sobre el sofá. creo que ((PERS)cojines) estan sobre el sofá'