gpt4 book ai didi

python - UnicodeEncodeError :'charmap' 与 'Ö' ,'Ç' 等

转载 作者:太空宇宙 更新时间:2023-11-03 11:26:00 26 4
gpt4 key购买 nike

我连接到 MySQL 并检索包含“Ö”、“ğ”、“Ş”等的用户名。它适用于 MySQL 或 PHP,但在 Python 2.6.8 中,会发生错误。这是我的代码:

#C:\Python27\Lib\encodings
#-*- coding: utf-8 -*-

conn = MySQLdb.Connect(host="localhost", user="root", passwd="mypass", db="mydb", charset="utf8", init_command="SET NAMES UTF8")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("select * from users");
tmpDict=cursor.fetchallDict()
print tmpDict[0]['NAME'].decode('utf8')

我希望这里出现“Ömer Şirin”,但我却收到以下错误:

'ascii' codec can't encode character u'\xd6' in position 0: ordinal not in range(128)

我该如何解决这个问题?

最佳答案

两个错误和两个问题:

  1. UnicodeEncodeError:'charmap' 与 'Ö'、'Ç' 等
  2. 'ascii' 编解码器无法对位置 0 中的字符 u'\xd6' 进行编码:序号不在范围内 (128)

如果 type(tmpDict[0]['NAME']) == unicode 那么第二个问题可以很容易地重现:

>>> u'\xd6'.decode('utf-8') #XXX BROKEN, DO NOT DO IT!!!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in position 0: ordinal not in range(128)

发生的事情是 u'\xd6' 已经是一个 Unicode 字符串,因此在对其进行解码之前,必须先将其转换为字节,Python 使用默认编码 ('ascii ') 来做到这一点。正确的解决方案是 drop .decode('utf-8') -- 不解码 Unicode 字符串(在 Python 3 中已修复) ,如果你尝试解码 Unicode 字符串,你会得到 AttributeError

第一个问题“UnicodeEncodeError:'charmap'” 可能是由于将 Unicode 打印到 Windows 控制台。要重现,请运行 print u'\xd6'。要修复它,install win-unicode-console .

关于python - UnicodeEncodeError :'charmap' 与 'Ö' ,'Ç' 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com