【问题标题】:Utf8 encoding with MySQLdb on non-utf symbols在非 utf 符号上使用 MySQLdb 进行 Utf8 编码
【发布时间】:2012-06-24 23:43:59
【问题描述】:

我收到一个 xml 提要,它的值如下:

<Theme>Valentine&#39;s Day</Theme>
<Copyright>&#169; Ventures. All Rights Reserved.</Copyright>

我需要解析值并将其存储在 mysql 数据库中。清理值的最佳方法是什么,以便我可以插入 "Valentie's Day""&lt;copyright symbol&gt; Ventures. All Rights Reserved."?这样的标记大约有 20 多种。

直接INSERT,我会得到以下错误:

Warning: Incorrect string value: '\xA9 1987...' for column 'title' at row 1

【问题讨论】:

    标签: python mysql unicode encoding utf-8


    【解决方案1】:

    如果您使用真正的 xml 解析器解析 XML,您将获得 Unicode 字符串作为文本。然后,您可以使用 UTF-8 对它们进行编码:

    title = text.encode('utf8')
    

    并且标题将可写入您的数据库,但许多细节仍不清楚,因为我们不知道您是如何写入数据库的。

    【讨论】:

      【解决方案2】:

      指定编码,然后将字符串编码为utf8

      # -*- coding: utf-8 -*-
      title = text.encode('utf8')
      

      【讨论】:

      • 文件编码在这里无关紧要,它只影响字符串文字的解释方式。
      猜你喜欢
      • 2015-03-07
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2014-12-09
      • 2015-10-26
      • 2011-05-12
      • 2015-03-23
      相关资源
      最近更新 更多