python - Python 的 Dominate 库中是否有类似于 .replace() 的函数?
问题描述
我想将 HTML 标记添加到从 .txt 文件中获取的文本中,然后另存为 HTML。我正在尝试查找特定单词的任何实例,然后将其“替换”为锚标记内的相同单词。
像这样的东西:
import dominate
from dominate.tags import *
item = 'item1'
text = ['here is item1 in a line of text', 'here is item2 in a line too']
doc = dominate.document()
with doc:
for i, line in enumerate(text):
if item in text[i]:
text[i].replace(item, a(item, href='/item1'))
上面的代码给出了一个错误:
类型错误:replace() 参数 2 必须是 str,而不是 a。
我可以做到这一点:
print(doc.body)
<body>
<p>here is item1 in a line of text</p>
<p>here is item2 in a line too</p>
</body>
但我想要这个:
print(doc.body)
<body>
<p>here is <a href='/item1'>item1</a> in a line of text</p>
<p>here is item2 in a line too</p>
</body>
解决方案
Dominate 中没有 replace() 方法,但此解决方案适用于我想要实现的目标:
- 将锚标记创建为字符串。存储在变量“item_atag”中:
item = 'item1'
url = '/item1'
item_atag = '<a href={}>{}</a>'.format(url, item)
- 使用 Dominate 库将段落标签包裹在原始文本中的每一行周围,然后转换为字符串:
text = ['here is item1 in a line of text', 'here is item2 in a line too']
from dominate import document
from dominate.tags import p
doc = document()
with doc.body:
for i, line in enumerate(text):
p(text[i])
html_string = str(doc.body)
- 使用 Python 内置的 replace() 方法为字符串添加锚标记:
html_with_atag = html_string.replace(item, item_atag)
- 最后,将新字符串写入 HTML 文件:
with open('html_file.html', 'w') as f:
f.write(html_with_atag)
推荐阅读
- salesforce - Salesforce 入站短信集成
- ios - 为什么 SQLite 方法“sqlite3_step”不起作用
- android - 电池优化不适用于某些应用程序。怎么可能?
- image - 通过在 React Native 中的 TouchableOpacity 中添加图像来制作圆形图像按钮
- java - 基于Java中的其他字段值验证必填字段的优化方法是什么?
- java - Springboot 版本从 2.1.6 升级到 2.2.1 和 spring-cloud 问题
- c++ - 测试框架意外退出:cat: /tmp/tmp.z5uNpMUXj6: No such file or directory
- scala - 在 scalacheck 中生成递归结构
- node.js - 似乎没有进行角度代理调用
- javascript - 如何累积每个数字?JavaScript