繁体   English   中英

如何在python中用增量计数替换一些字符串

[英]How to replace a number of string with incremental count in python

我在字符串中有一些HTML代码(用于在浏览器中显示),其中包含任意数量的svg图像,例如:

<table>
  <tr>
    <td><img src="http://localhost/images/Store.Tools.svg"></td>
    <td><img src="http://localhost/images/Store.Diapers.svg"></td>
  </tr>
</table>

我想找到所有HTML链接并将它们替换为以下内容(以便将其作为电子邮件附加):

<table>
  <tr>
    <td><cid:image1></td><td><cid:image2></td>
  </tr>
</table>

SVG文件名可以具有任意数量的点,字符和数字。

在python中执行此操作的最佳方法是什么?

我将使用HTML解析器来查找所有img标签并替换它们。

使用BeautifulSoup示例,它是replace_with()

from bs4 import BeautifulSoup

data = """
<table><tr>
<td><img src="http://localhost/images/Store.Tools.svg"></td>
<td><img src="http://localhost/images/Store.Diapers.svg"></td>
</tr></table>
"""

soup = BeautifulSoup(data, 'html.parser')
for index, image in enumerate(soup.find_all('img'), start=1):
    tag = soup.new_tag('img', src='cid:image{}'.format(index))
    image.replace_with(tag)

print soup.prettify()

打印:

<table>
 <tr>
  <td>
   <img src="cid:image1"/>
  </td>
  <td>
   <img src="cid:image2"/>
  </td>
 </tr>
</table>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM