Python 字符编码 欧式重音
我知道这个问题并不罕见,网上已经有很多相关的讨论(比如1、2、3),但即使按照那些建议去做,我还是遇到了这个错误(下面的代码):
uri_name = u"%s_%s" % (name[1].encode('utf-8').strip(), name[0].encode('utf-8').strip())
错误信息是:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128
我想从一组艺术家名字中生成一个网址,很多名字都有重音符号和一些欧洲字符(它们的名字也通过repr
显示了特殊字符):
Auberjonois, René -> Auberjonois, Ren\xc3\xa9
Bäumer, Eduard -> B\xc3\xa4umer, Eduard
Baur-Nütten, Gisela -> Baur-N\xc3\xbctten, Gisela
Bösken, Lorenz -> B\xc3\xb6sken, Lorenz
Čapek, Josef -> \xc4\x8capek, Josef
Großmann, Rudolf -> Gro\xc3\x9fmann, Rudolf
我尝试运行的代码块是:
def create_uri(artist_name):
artist_name = artist_name
name = artist_name.split(",")
uri_name = u"%s_%s" % (name[1].encode('utf-8').strip(), name[0].encode('utf-8').strip())
uri = 'http://example.com/' + uri_name
print uri
create_uri('Name, Non_Accent')
create_uri('Auberjonois, René')
第一个代码块运行正常,生成了http://example.com/Non_Accent_Name
,但第二个代码块却出现了上面的错误。
我在脚本的顶部加了# coding=utf-8
,并且在每个环节都尝试对artist_name
字符串进行编码,但每次都得到同样的错误。
如果这有影响的话,我使用的是Atom文本编辑器,当我打开这些名字来源的.csv文件时,重音符号都能正确显示。
我还可以做些什么来确保脚本将UTF-8正确识别为UTF-8,而不是ascii呢?
2 个回答
1
从你打印出来的内容来看,你正在使用 Python 2.x 版本。这意味着你需要用 \u
这种方式来定义 Unicode 字符,或者在字符串前加一个 u
的前缀。所以,你只需要把你的代码改成:
create_uri(u'Auberjonois, René') # note the u''
另外,看起来你在分割后不需要再用 .encode 了,因为它已经是 Unicode 了。
1
别再使用UTF-8了。到处都用unicode
,只有在接口处才进行解码或编码(如果需要的话)。
def create_uri(artist_name):
name = artist_name.split(u",")
uri_name = u"%s_%s" % (name[1].strip(), name[0].strip())
uri = u'http://example.com/' + uri_name
print uri
create_uri(u'Name, Non_Accent')
create_uri(u'Auberjonois, René')