在Python的Dominate模块中是否有类似于.replace()的函数?

问题描述 投票:1回答:1

我想将HTML标签添加到.txt文件中的文本中,然后另存为HTML。我正在尝试查找某个特定单词的任何实例,然后在锚标签中用相同的单词“替换”它。

类似这样的东西:

import dominate
from dominate.tags import *

item = 'item1'
text = ['here is item1', 'here is item2']
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()参数2必须是str,而不是a。

我可以做到这一点:

print(doc.body)

<body>
  <p>here is item1</p>
  <p>here is item2</p>
</body>

但是我想要这个:

 print(doc.body)

<body>
  <p>here is <a href='/item1'>item1</a></p>
  <p>here is item2</p>
</body>
python html replace text-files dominate
1个回答
0
投票

[如果您只想创建HTML元素(在这种情况下,是将段落<a>中的锚点<p>包裹起来),则可以直接实例化它们using only constructors like this

from dominate.tags import p, a

var = p("here is", a('item1', href="/item1"))

注意,HTML元素不是字符串,它是您从Dominate库中导入的p object的实例(使用调试器进行验证)。如果要将其转换为字符串,请使用Python内置的str()函数或Dominate render()方法。

var = p("here is", a('item1', href="/item1"))
one_str = str(var)
two_str = var.render()

[请注意,您的pa对象的字符串转换包含新行\n和空格。看起来像这样:

<p>here is\n  <a href="/item1">item1</a>\n</p>

是否要删除这些用途:

one_str = one_str.replace('\n  ', '')
one_str = one_str.replace('\n', '')

哪个给:

<p>here is<a href="/item1">item1</a></p>

话虽如此,将元素既保存在文档中,又保存在原始文本列表中:

from dominate import document
from dominate.tags import p, a

item = 'item1'
text = ['here is item1', 'here is item2']

doc = document()

with doc.body:

    for i, line in enumerate(text):

        # builds and inserts HTML elements into document.
        if item in text[i]:
            p(text[i].replace(item, ''), a(item, href='/' + item))
        else:
            p(text[i])

        # the same as above but inserts into list text as strings
        if item in text[i]:
            text[i] = str(p(text[i].replace(item, ''), a(item, href='/' + item)))
        else:
            text[i] = str(p(text[i]))

print(doc.body)
print(text)

以及结果,文档正文:

<body>
  <p>here is 
    <a href="/item1">item1</a>
  </p>
  <p>here is item2</p>
</body>

包含更新的字符串的原始文本列表:

text = ['<p>here is \n  <a href="/item1">item1</a>\n</p>', '<p>here is item2</p>']

最后注:

是否有类似于Dominate中的.replace()的功能>

您正在考虑的replace()方法适合Python strings。请注意,您使用textis a list数据结构没有replace()方法,但是可以使用Indexed Assignment直接访问和设置其元素。

最后,在这种情况下,只需在specific with keyword块中将它们声明为with,就可以在Dominate文档中包括HTML子元素。

© www.soinside.com 2019 - 2024. All rights reserved.