操作后查找并替换正则表达式项?

我想做的是这个(伪代码):


search for [[phrase//<img src="example.jpg" />//description (if applicable)]]

replace with:

<a>phrase

<div>Description<br><img src="example.jpg"></div>

</a>

例如,我想转换这个:


[[transvaginal pudendal nerve block//<img src="3bc9e18a9fa82a1bd4e0c8c580909389.jpg" />//image of transvaginal pudendal nerve block]]

对此:


<a>transvaginal pudendal nerve block

<div>image of transvaginal pudendal nerve block<br><img src="3bc9e18a9fa82a1bd4e0c8c580909389.jpg" /></div>

</a>

到目前为止,这是我的代码:


import re


answer_string = open("answer.txt", "r").read()

pattern = re.compile(r"\[\[.*\]\]")


for raw_material in re.findall(pattern, answer_string):

    copy_material = raw_material

    copy_material = copy_material.replace("[[", "")

    copy_material = copy_material.replace("]]", "")

    copy_material = copy_material.split("//")


    if len(copy_material) >= 3:

        raw_material = "<a>" + copy_material[0] + "<div>" + copy_material[2] + "<br>" + copy_material[1] + "</div></a>"

    else:

        raw_material = "<a>" + copy_material[0] + "<div>" + copy_material[1] + "</div></a>"


with open('new_answer.txt','w') as f:

  f.write(answer_string)

  f.close()

我以为通过设置raw_material =我可以立即更改短语,但我想不会。有点困惑我如何用正则表达式找到一些东西,操纵它,然后替换这个短语。


慕虎7371278
浏览 171回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python