首页 > 解决方案 > UnicodeEncodeError:“ascii”编解码器无法在位置 34 编码字符 u'\u05a0':序数不在范围内(128)

问题描述

我正在尝试在 python 中运行一段代码,我必须在其中读取包含 Json 格式代码的 filename.txt 文件。但是我在 json 值中有一些 Unicode 值。该文件非常大,但我在文件中找到了一个 Unicode 作为֠这个符号,其 Python 的 unicode 是u"\u05A0"

您可以参考此链接以获取有关 unicode Unicode 字符 'HEBREW ACCENT TELISHA GEDOLA' (U+05A0)的更多信息

我的 Python 代码看起来像

import MySQLdb
import json



db = MySQLdb.connect(host="10.233.188.84",    # your host, usually localhost
                 user="root",         # your username
                 passwd="freebird@123",  # your password
                 db="Practice_For_Json",)        # name of the data base


#cursor = db.cursor()
json_file = open('asda.txt', 'r' )
file_data = json.load(json_file)
print(file_data)
print(type(file_data))

datas = file_data['datads']
print(datas)
for data in datas:
    ex_statement = "Insert into `tablename` values {first_col '"+str(data['first_col'])+"'}, {second_col  '"+str(data['second_col'])+"'});"
#    cursor.execute(ex_statement)


db.close()

我的 Json 看起来像:

{"datads" :[{
      "first_col" : "SoomeVAlue_1",
      "second_col" : "SomeValue_1_1"
},
{
     "first_col" : " Unicode_Start ֠  Unicode_End",
     "second_col" : "SomeValue_2_2"
}]}

上面代码的输出是:

{u'datads': [{u'first_col': u'SoomeVAlue_1', u'second_col': u'SomeValue_1_1'}, {u'first_col': u' Unicode_Start \u05a0  Unicode_End', u'second_col': u'SomeValue_2_2'}]}
<type 'dict'>
[{u'first_col': u'SoomeVAlue_1', u'second_col': u'SomeValue_1_1'}, {u'first_col': u' Unicode_Start \u05a0  Unicode_End', u'second_col': u'SomeValue_2_2'}]
Traceback (most recent call last):
  File "abc.py", line 21, in <module>
    ex_statement = "Insert into `tablename` values {first_col '"+str(data['first_col'])+"'}, {second_col  '"+str(data['second_col'])+"'});"




UnicodeEncodeError: 'ascii' codec can't encode character u'\u05a0' in position 15: ordinal not in range(128)

当我运行此代码时,我收到错误作为标题。
我在 SSH shell 中使用 Python 2.7。
请帮我解决一下这个。

标签: pythonunicode

解决方案


在 Python2 中处理 unicode 时,确保所有字符串都是unicode字符串很重要,否则会出现问题。因此,这条线是有问题的:

ex_statement = "Insert into `tablename` values {first_col '"+str(file_data['first_col'])+"'}, {second_col file_data '"+str(['first_col'])+"'});"

如果 unicode 不包含非 ascii 字符,则调用strunicode 对象会导致 a 。UnicodeEncodeError所以

str(file_data['first_col'])

应该

unicode(file_data['first_col'])

为避免 Python 可能破坏最终字符串,所有字符串文字都应通过在它们前面加上 unicode 文字u,例如

u"Insert into `tablename` values {first_col '"

这些步骤将确保您的语句是 unicode。根据您的数据库配置,一个 unicode 语句可能会起作用,或者您可能需要将该语句编码为数据库所需的任何编码。

最后,像这样手动创建语句是不安全的,并且很难正确看待参数替换。正确构造的语句可能如下所示:

ex_statement = u"INSERT INTO MYTABLE (col1, col2) VALUES (%s, %s)"
cursor.execute(ex_statement, (u'foo', u'bar'))

推荐阅读