UnicodeEncodeError:“latin-1”编解码器无法对字符 u'\u2014' 进行编码

问题描述 投票:0回答:4

我收到此错误 UnicodeEncodeError: 'latin-1' 编解码器无法编码字符 u'\u2014'

我正在尝试将大量新闻文章加载到 MySQLdb 中。然而,我在处理非标准字符时遇到了困难,对于各种字符,我收到了数百个此类错误。我可以使用 .replace() 单独处理它们,尽管我想要一个更完整的解决方案来正确处理它们。

ubuntu@ip-10-0-0-21:~/scripts/work$ python test_db_load_error.py
Traceback (most recent call last):
  File "test_db_load_error.py", line 27, in <module>
    cursor.execute(sql_load)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 157, in execute
    query = query.encode(charset)
UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2014' in position 158: ordinal not in range(256)

我的脚本;

import MySQLdb as mdb
from goose import Goose
import string
import datetime

host = 'rds.amazonaws.com'
user = 'news'
password = 'xxxxxxx'
db_name = 'news_reader'
conn = mdb.connect(host, user, password, db_name)

url = 'http://www.dailymail.co.uk/wires/ap/article-3060183/Andrew-Lesnie-Lord-Rings-cinematographer-dies.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490'
g = Goose()
article = g.extract(url=url)
body = article.cleaned_text
body = body.replace("'","`")
load_date = str(datetime.datetime.now())
summary = article.meta_description
title = article.title
image = article.top_image

sql_load = "insert into articles " \
        "    (title,summary,article,,image,source,load_date) " \
        "     values ('%s','%s','%s','%s','%s','%s');" % \
        (title,summary,body,image,url,load_date)
cursor = conn.cursor()
cursor.execute(sql_load)
#conn.commit()

如有任何帮助,我们将不胜感激。

python mysql unicode
4个回答
7
投票

创建 mysqldb 连接时,将

charset='utf8'
传递给连接。

conn = mdb.connect(host, user, password, db_name, charset='utf8')

2
投票

如果您的数据库实际上配置为 Latin-1,则您无法在其中存储非 Latin-1 字符。其中包括 U+2014、EM DASH

理想的解决方案是切换到配置为 UTF-8 的数据库。只需在最初创建数据库时以及每次连接数据库时通过

charset='utf-8'
即可。 (如果你已经有现有数据,你可能想使用 MySQL 工具将旧数据库迁移到新数据库,而不是 Python 代码,但基本思想是相同的。)

但是,有时这是不可能的。也许您有其他无法更新、需要 Latin-1 并且需要共享同一数据库的软件。或者,您可能以无法通过编程方式取消混合的方式混合了 Latin-1 文本和二进制数据,或者您的数据库太大而无法迁移,或者其他什么。在这种情况下,你有两个选择:

  • 在存储和搜索之前将字符串破坏性地转换为 Latin-1。例如,您可能想要将长破折号转换为

    -
    --
    ,或者也许这并不那么重要,您可以将所有非 Latin-1 字符转换为
    ?
    (速度更快且更方便)更简单)。

  • 提出一种编码方案,将非 Latin-1 字符偷运到数据库中。这意味着某些搜索变得更加复杂,或者无法直接在数据库中完成。


0
投票

这可能是一本繁重的读物,但至少让我开始了。

http://www.joelonsoftware.com/articles/Unicode.html


0
投票

您可以将 CHARLANG 选择放入您的 linux /root/home .profile

export LANG="en_US.utf8"
© www.soinside.com 2019 - 2024. All rights reserved.