我有一个包含一些字符串的列表(其中大部分是从sqlite3数据库获取的):
stats_list = ['Statistik \xc3\xb6ver s\xc3\xa5nger\n', 'Antal\tS\xc3\xa5ng', '1\tCarola - Betlehems Stj\xc3\xa4rna', '\n\nStatistik \xc3\xb6ver datak\xc3\xa4llor\n', 'K\xc3\xa4lla\tAntal', 'MANUAL\t1', '\n\nStatistik \xc3\xb6ver \xc3\xb6nskare\n', 'Antal\tId', u'1\tNiclas']
当我试图加入时:
return '\n'.join(stats_list)
我得到这个错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)
仅仅通过查看列表就可以知道为什么会发生这种情况吗?如果我循环浏览列表并将其打印到屏幕上,我会得到:
Statistik över sånger Antal Sång 1 Carola - Betlehems Stjärna Statistik över datakällor Källa Antal MANUAL 1 Statistik över önskare Antal Id 1 Niclas
这正是我所期望的,没有显示错误。(特殊字符是瑞典语)。
编辑:
我试试这个:
return '\n'.join(i.decode('utf8') for i in stats_list)
但它回来了:
Traceback (most recent call last):
File "./CyberJukebox.py", line 489, in on_stats_to_clipboard
stats = self.jbox.get_stats()
File "/home/nine/dev/python/CyberJukebox/jukebox.py", line 235, in get_stats
return self._stats.get_string()
File "/home/nine/dev/python/CyberJukebox/jukebox.py", line 59, in get_string
return '\n'.join(i.decode('utf8') for i in stats_list)
File "/home/nine/dev/python/CyberJukebox/jukebox.py", line 59, in <genexpr>
return '\n'.join(i.decode('utf8') for i in stats_list)
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 10: ordinal not in range(128)
编辑2:
建议的解决办法对我在翻译中很有效。但是当我执行代码的时候它就不起作用了。我不能把我的头缠在这上面。可能是我遗漏了一些明显的东西,所以我把整个方法粘贴在这里:
def get_string(self):
stats_list = [u'Statistik över sånger\n', u'Antal\tSång']
stats = sorted([(v, k) for k, v in self.song_stats.iteritems()], reverse=True)
for row in stats:
line = '%s\t%s' % row
stats_list.append(line)
stats_list.append(u'\n\nStatistik över datakällor\n')
stats_list.append(u'Källa\tAntal')
stats = sorted([(k, v) for k, v in self.exts_stats.iteritems()])
for row in stats:
line = '%s\t%s' % row
stats_list.append(line)
stats_list.append(u'\n\nStatistik över önskare\n')
stats_list.append(u'Antal\tId')
stats = sorted([(v, k) for k, v in self.wisher_stats.iteritems() if k != ''], reverse=True)
for row in stats:
line = '%s\t%s' % row
stats_list.append(line)
return '\n'.join(i.decode('utf8') for i in stats_list)
song_stats
、exts_stats
和wisher_stats
是类中的词典。
字符串用UTF-8编码。你需要
.decode
把它们转换成unicode
:使用“理解”对所有元素执行此操作:
Python抱怨它无法将字符串
'Statistik \xc3\xb6ver s\xc3\xa5nger\n'
转换为ASCII字符串。尝试用u
作为所有UNICODE字符串的前缀。您的问题可能是您将unicode字符串与字节字符串混合在一起。
“Edit 2”中的代码有几个unicode字符串被添加到
stats_list
:如果您尝试解码这些unicode字符串,您将得到一个
UnicodeEncodeError
。这是因为Python将首先尝试使用默认编码(通常是“ascii”)对字符串进行编码,然后再尝试对字符串进行解码。只有解码字节字符串才有意义。因此,首先,将函数中的最后一行更改为:
现在您需要检查添加到
stats_list
的其他字符串是否是byte字符串,并确保它们首先被正确解码为unicode字符串。所以在这三行后面加上
print type(line)
:然后在打印
<type 'str'>
的地方,将下面的行更改为:当然,如果它打印
<type 'unicode'>
,就不需要更改下面的行。这里一个更好的解决方案是检查词典
song_stats
、exts_stats
和wisher_stats
是如何创建的,并确保它们始终包含unicode字符串(或只包含ascii字符的字节字符串)。相关问题 更多 >
编程相关推荐