【问题标题】:Write in a file with Python 3 & unicode使用 Python 3 和 unicode 写入文件
【发布时间】:2011-06-25 14:48:56
【问题描述】:

这是我的代码:

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()

但我给了我:

Une déclaration à faire ?鼓励吗?巴黎大队 d'élite beat agent est là pour vous aider。 Faites appel à nous en 上诉人 le 06 et nous accourrons vous 鼓励者 dans l'instant。 ñ hésitez 山口Et pour vous aider durant cette soirée, 瞧 accroche a tester, succès garanti :

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

【问题讨论】:

    标签: file unicode python-3.x encode


    【解决方案1】:

    您的症状看起来像常规的“UTF-8 as 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/

    【讨论】:

      【解决方案2】:

      似乎 python 不明白你的源代码是什么编码。你必须告诉它,要么使用字节顺序标记(首选),要么通过在第一行或第二行使用特殊注释声明类型。所以:

      1. 告诉您的编辑器在源代码中存储字节顺序标记,或者,如果它不能这样做
      2. 在包含 (IIRC) encoding: utf-8 的开头添加评论。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-17
        • 2017-09-07
        • 2012-08-30
        • 2017-06-03
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        相关资源
        最近更新 更多