代码之家  ›  专栏  ›  技术社区  ›  Jason R. Coombs

如何构建像PostgreSQL那样对字符串排序的Python比较器?

  •  1
  • Jason R. Coombs  · 技术社区  · 7 年前

    这个问题本质上与 this question ,Python除外。

    我希望查询按电子邮件地址列排序的PostgreSQL数据库中的行,然后使用Python执行依赖于该排序的操作。

    en_US.UTF8 通过一些测试,我发现排序规则在 @ 电子邮件地址中的符号:

    mydb=> SELECT '0'  < '@';
     ?column? 
    ----------
     f
    (1 row)
    
    mydb=> SELECT '0'  < '@0';
     ?column? 
    ----------
     t
    (1 row)
    

    This answer @ t 来自第二个查询。

    locale module ,该模块具有 inconsistent behavior on some platforms ,因此我似乎无法将该模块用于此目的。

    基于该报告,我尝试了使用 PyICU package

    >>> import icu
    >>> collator = icu.Collator.createInstance()
    >>> collator.getLocale()
    <Locale: en_US>
    >>> collator.getSortKey('0') < collator.getSortKey('@')
    False
    >>> collator.getSortKey('0') < collator.getSortKey('@0')
    False
    

    但正如你所看到的,在最后的比较中,它产生的顺序与博士后不同。

    我尝试为查询指定不同的排序规则,例如:

    SELECT email COLLATE posix FROM mytable ORDER by email;
    

    但这会导致一个错误: collation "posix" for encoding "UTF8" does not exist . 我还试着整理一下 "en-us-x-icu" ,但这也不存在。

    1 回复  |  直到 7 年前
        1
  •  2
  •   klin    7 年前

    使用 collate "C" 在研究生阶段:

    with test(test) as (
    values ('@'), ('@0'), ('0')
    )
    
    select test
    from test
    order by test collate "C"
    
     test 
    ------
     0
     @
     @0
    (3 rows)
    

    蟒蛇:

    >>> test = ['@', '@0', '0']
    >>> test.sort()
    >>> test
    ['0', '@', '@0']