0

我有一个像这样的数据库查询,我在 Postgres 数据库上的 Python 中执行:

"Select * from my_tbl where big_string like '%Almodóvar%'"

但是,在我正在搜索的列Almodóvar中表示为“ Almod\u00f3var”,因此查询不返回任何内容。

我该怎么做才能使两个字符串匹配?宁愿Almodóvar在 Python 端而不是数据库中的列上工作,但我很灵活。

评论提示的附加信息:

数据库使用 UTF-8。我正在查询的字段是从外部 API 获取的。数据作为 json 以 RESTfully 方式检索,然后在 json.dump 之后插入到数据库的文本字段中。

由于数据包含大量外来名称和字符,因此使用它一直是一系列与编码相关的难题。如果有一个灵丹妙药可以让这些数据与 Python 配合得很好,我会非常感激知道那是什么。

更新 2:

看起来是 json 编码让我陷入了困境。

print json.dumps("Almodóvar")

产量

"Almod\u00f3var"

这是我在查看原始数据时看到的。但是,当我使用 json.dumps 来构造它时:

"Select * from my_tbl where big_string like '%Almod\u00f3var%'"

查询仍然没有产生任何结果。我难住了。

4

3 回答 3

2

来自帮助(json.dumps):

If ``ensure_ascii`` is false, all non-ASCII characters are not escaped, and
the return value may be a ``unicode`` instance. See ``dump`` for details.

来自帮助(json.loads):

If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.

所以尝试类似的东西

>>> js = json.dumps("Almodóvar", ensure_ascii=False)  
>>> res = json.loads(js, encoding="utf-8")
>>> print res
Almodóvar
于 2013-08-11T21:16:27.300 回答
1

您的问题似乎来自查询之前的一步。从您从 Web 服务检索数据的时间开始。它可能是:

  • 在与 Web 服务通信期间,编码未设置为 UTF-8。
  • tmdb.org 端的编码不是 UTF-8(我不确定)。

我会先从第二种可能性开始研究这两点。

于 2013-08-11T20:46:28.867 回答
0

将您的 postgres 表的字符编码设置为 utf-8,然后它将与 python 顺利集成。无需来回转换。您的问题看起来像您对 python 代码和数据库使用两种不同的编码。

编辑:Almod\u00f3var 在我看来就像 Windows 代码页 1252。

于 2013-08-11T20:09:49.420 回答