![](/img/trans.png)
[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 32: ordinal not in range(128)
[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 47: ordinal not in range(128)
我使用的是Python 2.7和MySQLdb 1.2.3。 我嘗試了在stackoverflow和其他論壇上找到的所有內容來處理我的腳本拋出的編碼錯誤。 我的腳本從源MySQL DB中的所有表中讀取數據,將它們寫入python StringIO.StringIO
對象,然后將該數據從StringIO
對象加載到Postgres數據庫(顯然是UTF-8編碼格式。我通過查找找到了這個進入屬性 - 使用psycopg2庫的copy_from命令定義pgadmin中的數據庫。
我發現我的源MySQL數據庫在latin1_swedish_ci編碼中有一些表,而其他表用utf_8編碼格式(在information_schema.tables中找到這個來自TABLE_COLLATION)。
我根據我在互聯網上的研究,在Python腳本的頂部編寫了所有這些代碼。
db_conn = MySQLdb.connect(host=host,user=user,passwd=passwd,db=db, charset="utf8", init_command='SET NAMES UTF8' ,use_unicode=True)
db_conn.set_character_set('utf8')
db_conn_cursor = db_conn.cursor()
db_conn_cursor.execute('SET NAMES utf8;')
db_conn_cursor.execute('SET CHARACTER SET utf8;')
db_conn_cursor.execute('SET character_set_connection=utf8;')
我仍然使用以下行獲取下面的UnicodeEncodeError
: cell = str(cell).replace("\\r", " ").replace("\\n", " ").replace("\\t", '').replace("\\"", "") #Remove unwanted characters from column value
,
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 47: ordinal not in range(128)
在寫入StringIO對象時,我編寫了以下代碼行來清理源MySQL數據庫的每個表中的單元格。
cell = str(cell).replace("\r", " ").replace("\n", " ").replace("\t", '').replace("\"", "") #Remove unwanted characters from column value
請幫忙。
str(cell)
正在嘗試將cell
轉換為ASCII。 ASCII僅支持序數小於255的字符。什么是單元格?
如果cell
是unicode字符串,只需執行cell.encode("utf8")
,這將返回編碼為utf 8的字節字符串
......或者真的是iirc。 如果你傳遞mysql unicode,那么數據庫會自動將它轉換為utf8 ...
你也可以試試,
cell = unicode(cell).replace("\r", " ").replace("\n", " ").replace("\t", '').replace("\"", "")
或者只是使用第三方庫。 有一個很好的將為您修復文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.