【问题标题】:Python UnicodeEncodeErrorPython Unicode编码错误
【发布时间】:2013-08-19 14:58:21
【问题描述】:

我正在尝试使用此语句将一些数据插入 MySQL 数据库:

INSERT INTO tweets(tweeter,tweet)VALUES ('Lord_Sugar','RT @BTSport: This cerebral figure succeeds in insulting everyone’s intelligence. @CalvinBook looks at Kinnears impact on #NUFC http://t.…')

但我收到此错误:

UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2019' in position 119: ordinal not in range(256)

我知道它在谈论哪个角色——它在推文末尾的“……”,但不知道如何绕过它。

【问题讨论】:

  • print(repr('...')) 说角色由什么组成? '...' 是奇怪的字符。
  • 抱歉,那个字符不是 latin 1,它是别的东西,所以你需要将它解码为 erm 'iso-8859-15' 或直接运行。
  • Python2 还是 Python3 顺便说一句? (在这里有所作为)

标签: python mysql database python-2.7 python-unicode


【解决方案1】:

我猜你正在使用 MySQLDb 进行连接。

如果是这样,您应该在连接字符串中使用 charset 和 use_unicode 参数。 MySQLdb 默认使用 Latin-1:

import MySQLdb    
dbcon = MySQLdb.connect(user="root",db="twitter",use_unicode=True,charset='UTF8')

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    相关资源
    最近更新 更多