我想将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'))
上述代码给出了一个错误:
TypeError: replace() argument 2 must be str, not 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()方法,但此解决方案适用于我想要实现的目标:
相关问题 更多 >
编程相关推荐