【问题标题】:Python - Change string to utf8Python - 将字符串更改为 utf8
【发布时间】:2015-03-17 13:47:50
【问题描述】:

我正在尝试将葡萄牙语写入 HTML 文件,但我得到了一些有趣的字符。我该如何解决这个问题?

first = """<p style="color: red; font-family: 'Liberation Sans',sans-serif">{}</p>""".format(sentences1[i]) 
f.write(first)

预期输出: Hoje, nos nos unimos ao povo...

浏览器中的实际输出(Ubuntu 上的 Firefox): Hoje,nós nos unimos ao povo...

我试过这样做:

first = """<p style="color: red; font-family: 'Liberation Sans',sans-serif">{}</p>""".format(sentences1[i]) 
f.write(first.encode('utf8'))

终端输出: UnicodeDecodeError:“ascii”编解码器无法解码位置 65 的字节 0xef:序数不在范围内(128)

为什么会出现此错误,以及如何在没有有趣字符的情况下将其他语言写入 HTML 文档?
或者,我可以使用上述字体格式写入其他文件类型吗?

【问题讨论】:

标签: python utf-8 ascii utf8-decode


【解决方案1】:

您的格式字符串也应该是 Unicode 字符串:

first = u"""<p style="color: red; font-family: 'Liberation Sans',sans-serif">{}</p>""".format(sentences1[i]) 
f.write(first)

【讨论】:

  • 我仍然收到此错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
  • 您的sentences1 列表来自哪里?你也可以发布它的代码吗?
  • @kedar Traceback(最近一次调用最后):文件“p.py”,第 80 行,在 first = u"""

    {}

    """.format(sentences1[i]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in范围(128)
  • @selcuk 这个sentences1 列表来自一个文件。每个句子都被读取并存储在列表中。我的代码在英文文本上完美运行。如果我尝试用不同的语言写作,我会得到有趣的符号。所以我尝试更改编解码器,然后出现错误。
  • 读取文件时是否根据文件的编码进行解码?
【解决方案2】:

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

^ 阅读!

当您尝试对从具有特殊字符的文件中读取的文本使用.format 时,会发生这种情况。

>>> mystrf = u'special text here >> {} << special text'
>>> g = open('u.txt','r')
>>> lines = g.readlines()
>>> mystrf.format(lines[0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
>>>

Python 尝试将文件中的文本解码为 ASCII。那么我们该如何解决呢。

我们只是告诉 python 正确的编码。

>>> line = mystrf.format(lines[0].decode('utf-8'))
>>> print line
special text here >> ß << special text

但是当我们再次尝试写入文件时。它不起作用。

>>> towrite.write(line)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xdf' in position 21: ordinal not in range(128)

我们在再次写入文件之前对该行进行编码。

>>> towrite.write(line.encode('utf-8'))

【讨论】:

    【解决方案3】:

    看来您正在处理一个已经 UTF-8 编码的字符串,所以没关系。问题是 HTML 输出中的元标记将文本标识为 UTF-8 以外的内容。例如,您可能有&lt;meta charset="ISO-8859-1"&gt;;您需要将其更改为&lt;meta charset="UTF-8"&gt;

    这种字符集混淆的术语是Mojibake

    附:您的字符串以 Byte Order Mark (BOM) 开头,您可能希望在使用该字符串之前将其删除。

    【讨论】:

      猜你喜欢
      • 2018-10-05
      • 1970-01-01
      • 2017-03-30
      • 2020-10-11
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      相关资源
      最近更新 更多