Python的控制库中是否有类似于.replace()的函数?

2024-04-26 14:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将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>

Tags: oftextin标记dochereishtml
1条回答
网友
1楼 · 发布于 2024-04-26 14:23:17

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

  1. 将锚定标记创建为字符串。存储在变量“item_atag”中:
    item = 'item1'
    url = '/item1'
    item_atag = '<a href={}>{}</a>'.format(url, item)
  1. 使用控制库将段落标记环绕原始文本中的每一行,然后转换为字符串:
    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)

相关问题 更多 >