用 Python 语法操作,如何用一个正则把里面面各类图片替换成,这种统一的格式?

2020-03-08 00:03:44 +08:00
 python30
用 python 语法操作:


如果一段文本里可能含以下图片地址与文字等组合
<img src="http-url" alt="妹子" />
<img src="http-url" alt="妹子" style="height:auto !important;" />
<img src="http-url" alt="妹子" width="100%" />

http-url 为图片地址,
如何用一个正则把上面各类图片替换成:

<mip-img src="http-url" alt="妹子" ></mip-img>

这种统一的形式。

不知道有没有一个正则可以把全部图片地址,都统一替换成:

<mip-img src="http-url" alt="妹子" ></mip-img>

这种格式。

单一的好写。是全部的总是不成功。

哪位朋友指导一下,谢谢。
2858 次点击
所在节点    Python
12 条回复
zhzy
2020-03-08 00:20:27 +08:00
好奇“单一的好写但是全部的不成功”是什么情况😳
python30
2020-03-08 00:24:22 +08:00
@zhzy
只把
<img src="http-url" alt="妹子" />
这一个替换可以成功
要是<img 里面还很多其它参数之类的就不成功了
zhzy
2020-03-08 00:31:52 +08:00
@python30 加个 .*? 不就可以了么 关键词贪婪匹配
PTLin
2020-03-08 00:37:10 +08:00
def foo(s):
template='<mip-img src="{0[0]}" alt="{0[1]}" ></mip-img>'
m=re.match(r'.*src=\"(.*?)\"\s*alt=\"(.*?)\".*',s)
if m is not None:
return template.format(m.groups())
ysc3839
2020-03-08 06:26:13 +08:00
如果没有特殊限制,建议解析 html 再处理。
ClericPy
2020-03-08 11:47:40 +08:00
python30
2020-03-08 12:08:25 +08:00
@PTLin
@ClericPy
谢谢。我测试一下。
iRocW
2020-03-09 17:03:09 +08:00
只要提取 src alt 重写 不就好了?
l4ever
2020-03-10 20:57:45 +08:00
```
from bs4 import BeautifulSoup

if __name__ == "__main__":
html = """
<img src="http-url" alt="妹子" />
<img src="http-url" alt="妹子" style="height:auto !important;" />
<img src="http-url" alt="妹子" width="100%" />
"""

soup = BeautifulSoup(html, 'html.parser')
img = soup.find_all('img')
for i in img:
src = i.attrs['src']
alt = i.attrs['alt']
print(f'<mip-img src="{src}" alt="{alt}" ></mip-img>')

```
l4ever
2020-03-10 20:58:08 +08:00
为什么回复不支持 markdown?
l4ever
2020-03-10 20:59:21 +08:00
python30
2020-03-11 11:00:24 +08:00
@l4ever 谢谢。已经解决了。根据 @ClericPy 这朋友写的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/650818

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX