1

希望我能在这里找到一些答案。我正在尝试使用 python 3 编写 html。我尝试过 yattag 和主控模块,但两者都有相同的问题:当我尝试将代码内容写入 HTML 文件时,生成的文档不显示带有重音符号的字母,而是显示一个黑色小图形中的问号。(见底部图片)

我的代码看起来像这样。

使用支配:

import dominate
import dominate.tags as tg
#an example doc
_html = tg.html(lang='es')
_head = _html.add(tg.head())
_body = _html.add(tg.body())
with _head:
    tg.meta(charset="UTF-8") #this line seems to be the problem
with _body:
    tg.p("Benjamín")
print(_html)
#when I print to console, the accent mark in the letter 'í' is there but...
#when I write the file, the weird character is displayed 

with open("document.html", 'w') as file:
    file.write(_html.render())

同样的事情使用 yattag

from yattag import Doc
#another example doc
doc, tag, text = Doc().tagtext()
with tag("html", "lang='es'"):
    with tag("head"):
        doc.stag("meta", charset="UTF-8") #this line seems to be the problem
    with tag("body"):
        text("Benjamín")
#when I print to console, the accent mark in the letter 'í' is there but...
#when I write the file, the weird character is displayed 
with open("document2.html", 'w') as file:
    file.write(doc.getvalue())

因此,当我在这两种情况下更改或删除字符集时,问题似乎就消失了。我使用最后两行来编写简单的文档,我猜每个人都这样做,并且重音符号没有问题。问题似乎是导入的模块如何管理字符集以显示页面内容。嗯,我不知道。你知道有什么办法可以解决这个问题吗?希望你一切都好。谢谢你。

你可以看到这个烦人的符号

4

1 回答 1

2

您可以在文件encoding时使用该参数open

with open("document2.html", 'w', encoding='utf-8') as file:

专业提示:您可以使用errors参数定义出现错误时的行为:

with open("document2.html", 'w', encoding='utf-8', errors='ignore') as file:
于 2020-07-16T01:23:09.377 回答