首页 > 解决方案 > 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>

标签: pythonhtmlreplacetext-filesdominate

解决方案


Dominate 中没有 replace() 方法,但此解决方案适用于我想要实现的目标:

  1. 将锚标记创建为字符串。存储在变量“item_atag”中:
    item = 'item1'
    url = '/item1'
    item_atag = '<a href={}>{}</a>'.format(url, item)
  1. 使用 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)
  1. 使用 Python 内置的 replace() 方法为字符串添加锚标记:
    html_with_atag = html_string.replace(item, item_atag)
  1. 最后,将新字符串写入 HTML 文件:
    with open('html_file.html', 'w') as f:
        f.write(html_with_atag)

推荐阅读