首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python HTML重音标记问题与Yattag,支配

Python HTML重音标记问题与Yattag,支配
EN

Stack Overflow用户
提问于 2020-07-16 07:05:09
回答 1查看 223关注 0票数 1

希望我能在这里找到一些答案。我试着用python 3来写html,我试过yattag和dominate模块,但是我遇到了同样的问题:当我试图把代码的内容写到一个HTML文件中时,生成的文档不会显示带有重音符号的字母,而是会显示一个黑色的小问号。(见下图)

我的代码如下所示。

使用dominate:

代码语言:javascript
复制
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做同样的事情

代码语言:javascript
复制
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())

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-16 09:23:09

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

代码语言:javascript
复制
with open("document2.html", 'w', encoding='utf-8') as file:

Pro提示:您可以使用errors参数定义出错时的行为:

代码语言:javascript
复制
with open("document2.html", 'w', encoding='utf-8', errors='ignore') as file:
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62925017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档