Python MySQLdb 更改字符串编码

0 投票
3 回答
1009 浏览
提问于 2025-04-18 04:38

我觉得我的问题是,Python在处理SQL表中某一列的字符编码时不太顺利:

| column | varchar(255) | latin1_swedish_ci | YES  |     | NULL              |                             | select,insert,update,references |    | 

上面的内容显示了这一列的输出。它的类型是 varchar(255),编码是 latin1_swedish_ci.

现在,当我尝试用Python处理这些数据时,出现了以下错误:

 dictionary = gs.corpora.Dictionary(tweets)
  File "/usr/local/lib/python2.7/dist-packages/gensim-0.9.1-py2.7.egg/gensim/corpora/dictionary.py", line 50, in __init__
    self.add_documents(documents)
  File "/usr/local/lib/python2.7/dist-packages/gensim-0.9.1-py2.7.egg/gensim/corpora/dictionary.py", line 97, in add_documents
    _ = self.doc2bow(document, allow_update=True) # ignore the result, here we only care about updating token ids
  File "/usr/local/lib/python2.7/dist-packages/gensim-0.9.1-py2.7.egg/gensim/corpora/dictionary.py", line 121, in doc2bow
    document = sorted(utils.to_utf8(token) for token in document)
  File "/usr/local/lib/python2.7/dist-packages/gensim-0.9.1-py2.7.egg/gensim/corpora/dictionary.py", line 121, in <genexpr>
    document = sorted(utils.to_utf8(token) for token in document)
  File "/usr/local/lib/python2.7/dist-packages/gensim-0.9.1-py2.7.egg/gensim/utils.py", line 164, in any2utf8
    return unicode(text, encoding, errors=errors).encode('utf8')
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 0: invalid start byte

gs 是一个叫做 gensim 的主题建模库。我认为问题在于gensim需要使用unicode编码。

  1. 我该如何更改数据库中这一列的字符编码(排序规则)?
  2. 有没有其他解决方案?

谢谢大家的帮助!

3 个回答

0

我试了@saudi_Dev的解决方案,使用的是MySQLdb v1.2.5。我查询的表是用DEFAULT CHARSET=utf8创建的。尽管如此,在尝试@saudi_Dev的解决方案之前,cursor.fetchall()返回的字符串却莫名其妙的是latin1格式。使用了charset=utf8这个参数后,cursor.fetchall()返回的字符串变成了Unicode(技术上来说不是utf8),而不是latin1

不过我在http://mysql-python.sourceforge.net/MySQLdb.html上看到,你也可以传递参数use_unicode=False。根据我发的链接中的用户指南,这种情况发生是因为使用charset参数意味着use_unicode=True

2

对于问题1,你需要使用

alter table t 
modify col varchar(255) 
character set utf8
collate utf8_unicode_ci

我对问题2不太清楚。

3

我觉得你的MYSQLdb这个Python库不知道它应该用utf8编码。

所以它可能在用默认的Python系统字符集latin1来编码。

当你连接到数据库时,记得传递一个 charset='utf8' 的参数。

这样做也可以手动执行一个 SET NAMES 的命令。

撰写回答