Python - 将字符串更改为utf8

时间:2015-03-17 13:47:50

标签: python utf-8 ascii utf8-decode

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

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

预期产出: Hoje,nósnosunimos ao povo ...

浏览器中的实际输出(Ubuntu上的Firefox): Hoje,nósnosunimos 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文档? 或者,我可以用上面的字体格式写入不同的文件类型吗?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

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