我有一个文本文件(bio.txt),其中包含以下文本:
Enter for a chance to {win|earn|gain|obtain|succeed|acquire|get}
1 - Click {Link|Url|Link up|Site|Web link} Below
2 - Enter Name
3 - Do the submit(inside option {put|have|positioned|set|placed|apply|insert} address)我有这段python代码:
def spyntax():
bio_file = open('bio.txt', 'r').readlines()
_line = ''
for line in bio_file:
try:
matches = re.findall('\{([a-zA-Z| ]+)\}', line)
for march in matches:
tmp = random.choice(march.split('|'))
_line += re.sub('\{([a-zA-Z| ]+)\}', tmp, line)
except Exception as e:
print e
return _line代码查找文本的方式如下:
{win|earn|gain|obtain|succeed|acquire|get} 并替换为随机选择的文本组。问题是,如果在同一行中存在更多具有
{text|text} {word1|word2}那么python不会替换正确的{}。如何让此代码正确替换所有{}组?
发布于 2016-01-08 04:35:51
您可以将re.sub()与一个小帮助器函数相结合,从结果中选择一个随机字符串并将其用于sub:
import re
import random
s = "Enter for a chance to {win|earn|gain|obtain|succeed|acquire|get}"
def split_rand(r):
r = r.group(1)
return random.choice(r.split('|'))
print re.sub('{(.*?)}', lambda r: split_rand(r), s)如果你想得到更多的最小化,你可以删除这个函数,然后简单地:
re.sub('{(.*?)}', lambda r: random.choice(r.group(1).split('|')), s)因此,您可以将循环重新编写到程序中,以:
for line in biofile:
_line += re.sub('{(.*?)}', lambda r: random.choice(r.group(1).split('|')), line)https://stackoverflow.com/questions/34664354
复制相似问题