![](/img/trans.png)
[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 34: ordinal not in range(128)
[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\u05a0' in position 34: ordinal not in range(128)
我正在嘗試在python中運行一段代碼,我必須讀取包含Json格式代碼的filename.txt文件。 但我在json值中有一些Unicode值。 該文件非常大,但我發現文件中有一個Unicode為֠
這個符號,其Python的unicode是u"\֠"
有關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。
請幫我解決一下這個。
在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字符,則調用str
將使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'))
我想你可以試試這個,
json_file = open('test.txt','rb')
json_file = json_file.read().decode('UTF-8')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.