我试图在python中运行一段代码,在那里我必须读取一个包含Json格式代码的filename.txt文件。但我在json值中有一些Unicode值。这个文件非常大,但是我在文件中找到了一个Unicode作为֠,这个符号的unicode是u"\u05A0"
有关unicode Unicode字符‘希伯来口音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中使用Python2.7。
请帮我处理这个。
发布于 2019-04-22 10:29:07
在Python2中处理unicode时,必须确保所有字符串都是unicode字符串,否则就会出现问题。因此,这一行是有问题的:
ex_statement = "Insert into `tablename` values {first_col '"+str(file_data['first_col'])+"'}, {second_col file_data '"+str(['first_col'])+"'});"调用str时,如果unicode排除了非ascii字符,则unicode对象将导致UnicodeEncodeError。所以
str(file_data['first_col'])应该是
unicode(file_data['first_col'])为了避免Python潜在地破坏最终字符串,所有字符串文本都应该使用u前缀,从而使它们成为unicode文本。
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'))发布于 2019-04-22 10:10:16
我想你可以试试这个
json_file = open('test.txt','rb')
json_file = json_file.read().decode('UTF-8')https://stackoverflow.com/questions/55792483
复制相似问题