samedi 27 août 2022

Randomize Elements Positions Defined between "<" and ">" Symbols Using Regular Expressions

I am trying to randomize elements positions that are defined between "<" and ">" brackets, eg. from this

<id:1 s= red> 
<id:2 s= blue> 
<id:3 s= green>

to this

<id:3 s= green> 
<id:1 s= red> 
<id:2 s= blue>   

I put them in a list but can't match back the randomized list with the regex results. Here is what I got so far:

import re
from random import shuffle

a = open('data.txt', 'r')
s= a.read()
x = re.findall(r'\<([^>]+)', s)
shuffle(x)
f = re.sub(r'\<([^>]+)', x[0], s)


print(f)



Aucun commentaire:

Enregistrer un commentaire