我正试图随机化在"<quot;以及">quot;括号,例如。从这个
<id:1 s= red>
<id:2 s= blue>
<id:3 s= green>
到这个
<id:3 s= green>
<id:1 s= red>
<id:2 s= blue>
我把它们放在一个列表中,但无法将随机化列表与正则表达式结果进行匹配。到目前为止,我得到的是:
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)
尝试成功:
x = re.findall(r'(<[^>]+)', s)
shuffle(x)
f = re.sub(r'(<[^>]+)', lambda _: x.pop(), s)
我喜欢怎么做:
x = re.split(r'(<[^>]+)', s)
y = x[1::2]
shuffle(y)
x[1::2] = y
f = ''.join(x)
在线试用!