How to prevent a surplus of the substring used as separator by re.split from being left inside one of the resulting list items after string splitting?

Question:

import re

input_text = "Creo que ((PERS)los viejos gabinetes) estan en desuso, hay que hacer algo con ellos, ya que ellos son importantes. ellos quedaron en el deposito de ellos. ellos ((PERS)los cojines) son acolchonados, ellos estan sobre el sofá. creo que ellos estan sobre el sofá"

pattern = r"((PERS)s*loss*"
matches = re.findall(pattern, input_text)
result = re.split(pattern, input_text)

final_result = []
for i in range(len(matches)):
    if i == 0:
        final_result.append(result[i] + matches[i])
    else:
        final_result.append(matches[i-1] + result[i] + matches[i])
final_result.append(matches[-1] + result[-1])

final_result = [x.strip() for x in final_result if x.strip() != '']

print(final_result)

When dividing the strings to form the list, it makes the mistake of leaving a part of ((PERS)los in the element before the separation.

And consequently I get this wrong output:

['Creo que ((PERS)los', '((PERS)los viejos gabinetes) estan en desuso, hay que hacer algo con ellos, ya que ellos son importantes. ellos quedaron en el deposito de ellos. ellos ((PERS)los', '((PERS)los cojines) son acolchonados, ellos estan sobre el sofá. creo que ellos estan sobre el sofá']

Here is the problem:

que ((PERS)los', '((PERS)los viej

s. ellos ((PERS)los', '((PERS)los cojines) son ac

This should be the correct output:

['Creo que ', '((PERS)los viejos gabinetes) estan en desuso, hay que hacer algo con ellos, ya que ellos son importantes. ellos quedaron en el deposito de ellos. ellos ', '((PERS)los cojines) son acolchonados, ellos estan sobre el sofá. creo que ellos estan sobre el sofá']
Asked By: Matt095

||

Answers:

I think you’re overcomplicating the problem. Why not use split with a look-ahead as pattern?

import re

input_text = "Creo que ((PERS)los viejos gabinetes) estan en desuso, hay que hacer algo con ellos, ya que ellos son importantes. ellos quedaron en el deposito de ellos. ellos ((PERS)los cojines) son acolchonados, ellos estan sobre el sofá. creo que ellos estan sobre el sofá"
pattern = re.compile(r"(?=((PERS)s*loss*)")
print(re.split(pattern, input_text))

Output.

['Creo que ', '((PERS)los viejos gabinetes) estan en desuso, hay que hacer algo con ellos, ya que ellos son importantes. ellos quedaron en el deposito de ellos. 
ellos ', '((PERS)los cojines) son acolchonados, ellos estan sobre el sofá. creo que ellos estan sobre el sofá']
Answered By: Tranbi
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.