2017-04-02 19 views
0

我試圖從XML源中將數據發送到MySQL數據庫,但是我在python和mysql中出現錯誤的pt-br字符。在python中從xml中獲取pt-br中的錯誤字符

import MySQLdb 
import urllib2 
import sys 
import codecs 

## default enconding 
reload(sys) 
sys.setdefaultencoding('utf-8') 
UTF8Writer = codecs.getwriter('utf8') 
sys.stdout = UTF8Writer(sys.stdout) 
file = urllib2.urlopen('feed.xml') 
data = file.read() 
file.close() 
data = xmltodict.parse(data) 

db = MySQLdb.connect(host=MYSQL_HOST, # your host, usually localhost 
        user=MYSQL_USER,   # your username 
        passwd=MYSQL_PASSWD, # your password 
        db=MYSQL_DB)  # name of the data base 
cur = db.cursor() 

    product_name = str(data.items()[0][1].items()[2][1].items()[3][1][i].items()[1][1]) 

但是當我打印PRODUCT_NAME在Python或將其插入到MySQL的,我得到這個:

'Probi\xc3\xb3tica (120caps)' 

這應該是:

'Probiótica' 

我該如何解決這個問題?

回答

1

'Probi\xc3\xb3tica''Probiótica'的utf-8編碼版本。
你的終端(或者你用來運行這個的)是否被設置爲處理utf-8輸出?
嘗試print 'Probi\xc3\xb3tica'.decode('utf-8')看看會發生什麼。
我得到Probiótica

+0

我得到u'Probi \ xf3tica'。我使用OSx終端進行編碼。我如何編輯它以輸出正確的字符? –

+0

我檢查了首選項 - >高級和我的文本編碼是Unicode(UTF-8) –

+0

在這種情況下,我期望'print'Probi \ xc3 \ xb3tica''給出'Probiótica' - 這就是我在類似的配置。我上面的回答顯示了我使用Emacs運行Python。 – cco