0

我有一大块包含多个<img>标签的 HTML。标签的当前格式是:

<img width="580" height="183" src="/images/stories/acidalkalinetable.jpg" alt="acid alkaline table" title="Body pH Balance">

我想通过 html 并将每个<img>标签的格式更改为:

<img width="580" height="183" src="{{media url="wysiwyg/acidalkalinetable.jpg"}}" alt="acid alkaline table" title="Body pH Balance">

你可以看到它正在src改变。我保留了文件名,但更改了文件的其他部分src

如果 img 是单个字符串,我可以执行以下操作:

content = '<img width="580" height="183" src="/images/stories/acidalkalinetable.jpg" alt="acid alkaline table" title="Body pH Balance">'

filename = re.search(r'/images/stories/\w+\.(jpg|png|gif)', content)

new_content = re.sub(r'/images/stories/\w+\.(jpg|png|gif)', '{{media url="wysiwyg/' + filename + '"}}', content)

(我没有测试过)

但我不确定如何为<img>HTML 中每次出现的标签做到这一点

4

1 回答 1

2

您需要将文件名捕获为一个组,然后可以一次性替换它:

re.sub(r'/images/stories/([\w%]+\.(?:jpg|png|gif))', r'{{media url="wysiwyg/\1"}}', content)

这会在包括扩展名在内的整个文件名周围放置一个捕获组 ( (...))(它现在使用捕获组(?:...)),从而导致:

>>> re.sub(r'/images/stories/([\w%]+\.(?:jpg|png|gif))', r'{{media url="wysiwyg/\1"}}', content)
'<img width="580" height="183" src="{{media url="wysiwyg/acidalkalinetable.jpg"}}" alt="acid alkaline table" title="Body pH Balance">'

\1用作替换模式,请参阅re.sub()文档

re.sub()调用将使用语法替换所有匹配/images/stories/..的路径。{{media url="wisywig/.."}}

于 2013-03-19T17:30:05.693 回答