我在Python3.7中使用了主导模块,我不知道如何处理Python中存在的新行字符。根据我的要求,新的行字符\n应该转换为<br>中的中断字符。但这是不可能的。主导模块忽略换行符,这不是我期望它的表现。下面是我尝试过的代码。
import dominate
from dominate.tags import *
text = "Hello\nworld!"
doc = dominate.document(title='Dominate your HTML')
with doc:
h1(text)
with open("dominate22.html", 'w') as file:
file.write(doc.render())输出的HTML代码是
<!DOCTYPE html>
<html>
<head>
<title>Dominate your HTML</title>
</head>
<body>
<h1>Hello,
World!</h1>
</body>
</html>此外,我还尝试用中断字符(即text.replace("\n", "<br>") )替换新的行字符,但这是在创建一个像Hello<br>World这样的字符串,这与我所期望的不一样。附加相同的HTML代码。
<!DOCTYPE html>
<html>
<head>
<title>Dominate your HTML</title>
</head>
<body>
<h1>Hello<br>world</h1>
</body>
</html>发布于 2022-02-23 05:00:21
这个支配模块忽略了换行符,这不是我期望它的表现。
对于主导库,\n只是文本字符串中的一个字符。它与换行<br>元素不一样,所以您必须通过编程方式添加它。
此示例展示了两种方法,即使用上下文管理器和向实例添加节点:
import dominate
from dominate.tags import h1, h2, br
from dominate.util import text
the_string = "Hello\nworld!"
doc = dominate.document(title='Dominate your HTML')
with doc:
parts = the_string.split('\n')
with h1(): # using a context manager
text(parts[0])
br()
text(parts[1])
header = h2() # same as above but adding nodes
header.add(text(parts[0]))
header.add(br())
header.add(text(parts[1]))
with open("dominate22.html", 'w') as file:
file.write(doc.render())给出这个HTML:
<!DOCTYPE html>
<html>
<head>
<title>Dominate your HTML</title>
</head>
<body>
<h1>Hello<br>world!</h1>
<h2>Hello<br>world!</h2>
</body>
</html>https://stackoverflow.com/questions/69705342
复制相似问题