Jas*_*mbs 5 python postgresql collation
这个问题本质上与这个问题相同,除了Python。
我希望查询 PostgreSQL 数据库中按电子邮件地址列排序的行,然后在 Python 中执行依赖于该排序的操作。
我正在查询的数据库正在使用en_US.UTF8排序规则,经过一些测试,我发现该排序规则对于@电子邮件地址中的符号有一些特殊的行为:
mydb=> SELECT '0' < '@';
?column?
----------
f
(1 row)
mydb=> SELECT '0' < '@0';
?column?
----------
t
(1 row)
Run Code Online (Sandbox Code Playgroud)
这个答案表明@某些排序规则可能会忽略某个符号,但如果是这种情况,我预计t第二个查询会出现 a 。
尽管Python提供了一个语言环境模块,但该模块在某些平台上的行为不一致,因此我似乎无法使用该模块来实现此目的。
根据该报告,我尝试了使用PyICU 包的建议,这似乎很有希望:
>>> import icu
>>> collator = icu.Collator.createInstance()
>>> collator.getLocale()
<Locale: en_US>
>>> collator.getSortKey('0') < collator.getSortKey('@')
False
>>> collator.getSortKey('0') < collator.getSortKey('@0')
False
Run Code Online (Sandbox Code Playgroud)
但正如您所看到的,在最后的比较中,它产生的顺序与 postgres 不同。
我尝试为查询指定不同的排序规则,例如:
SELECT email COLLATE posix FROM mytable ORDER by email;
Run Code Online (Sandbox Code Playgroud)
但这会导致错误:collation "posix" for encoding "UTF8" does not exist。我还尝试了 的排序规则"en-us-x-icu",但也不存在。
有没有办法按照 Python 程序可以依赖的顺序可靠地从 PostgreSQL 查询一列电子邮件地址,无论是通过调整查询的排序规则还是遵循 Python 中的默认排序规则?
在 Postgres 中使用collate "C":
with test(test) as (
values ('@'), ('@0'), ('0')
)
select test
from test
order by test collate "C"
test
------
0
@
@0
(3 rows)
Run Code Online (Sandbox Code Playgroud)
Python:
>>> test = ['@', '@0', '0']
>>> test.sort()
>>> test
['0', '@', '@0']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
548 次 |
| 最近记录: |