gpt4 book ai didi

python - 使用 Python 在 Postgres 中搜索 json 编码的字符串

转载 作者:行者123 更新时间:2023-11-29 14:22:36 26 4
gpt4 key购买 nike

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

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

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

如何使两个字符串匹配?宁愿在 Python 端使用 Almodóvar 而不是数据库中的列,但我很灵活。

评论提示的附加信息:

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

由于数据包含大量外国名称和字符,处理这些数据一直是一系列与编码相关的令人头疼的问题。如果有什么 Elixir 可以让这些数据与 Python 兼容,我将非常感激知道那是什么。

更新 2:

看起来是 json 编码造成了我的窘境。

print json.dumps("Almodóvar")

产量

"Almod\u00f3var"

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

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

查询仍然没有结果。我很难过。

最佳答案

来自帮助(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

关于python - 使用 Python 在 Postgres 中搜索 json 编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com