使用Python 3和Unicode将内容写入文件

6

这是我的代码:

import codecs
filename = "worst.txt"
file = open(filename, "r",encoding='utf-8')
lines = file.readlines()
texte = ""
for line in lines:
    print(line)
    texte += line
file.close()
print(texte)
texte = texte.split(";")
print(texte)
filename = "oudean.html"



file = open(filename, "w",encoding='utf-8')



file.write("<html><body>\r\n")
for t in texte :
        print(t)
        file.write("""<img src="ouedan.jpg"><br>\r\n""")
        file.write("""Une déclaration à faire ?<br>Besoin d'encouragements?<br>Notre brigade d'élite beat agent est là pour vous aider.<br>Faites appel à nous en appelant le  06 et nous accourrons vous encourager dans l'instant.<br>N hésitez pas.<br>Et pour vous aider durant cette soirée, voilà une accroche a tester, succès garanti :<br>%s<br><br><br><br><br><br><br><br>"""%t)
file.write("</body></html>\r\n")
file.close()

但是我得到了:

有声明要发表吗?需要鼓励吗?我们的精英团队beat agent在这里为您提供帮助。拨打06号码并呼叫我们,我们将立即前来鼓励您。不要犹豫。为了帮助您度过这个晚上,这是一个测试成功的引语:

那么如何使用Unicode字符串写入文件?

2个回答

10

您的症状看起来像是常见的“UTF-8作为Latin-1”问题。

您是否检查了用于查看该文件的软件使用的编码格式?我认为问题不一定在您的Python代码中,而是在查看器中。

如果您使用UTF-8编码创建包含示例文本Une déclaration à faire...的文件,然后使用ISO-8859-1或windows-1252解释内容读取该文件,则显示的结果会如您所描述的输出:Une déclaration à faire...

此外,在Python 3中,默认源编码为UTF-8。 http://www.python.org/dev/peps/pep-3120/


0

看起来 Python 不理解你的源代码使用的编码方式。你需要告诉它,可以通过以下两种方式之一:使用字节顺序标记(首选)或在第一行或第二行使用特殊注释声明类型。因此:

  1. 告诉你的编辑器在源代码中存储字节顺序标记,或者如果它无法执行该操作
  2. 在开头放置一个包含(如果我没记错的话)encoding: utf-8的注释。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接