【问题标题】:`str.upper()` method does not respect `LC_CTYPE` setting, but `pyicu` does`str.upper()` 方法不遵守 `LC_CTYPE` 设置,但 `pyicu` 可以
【发布时间】:2020-07-26 13:38:26
【问题描述】:

使用 Python 自带的locale 模块和str.upper() 方法时,'istanbul'.upper() 返回的结果不正确。

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'tr_TR.UTF-8')
>>> 'tr_TR.UTF-8'
>>> s1 = 'istanbul'
>>> s1.upper()
'ISTANBUL'

如果我安装并使用pyicu,它会按预期工作。

>>> from icu import Locale, UnicodeString
>>> tr = Locale('tr_TR.UTF-8')
>>> s2 = UnicodeString('istanbul')
>>> str(s2.toUpper(tr))
'İSTANBUL'

如何确保 Python 的内置模块和方法在给定的语言环境下正常工作?

【问题讨论】:

    标签: python string unicode locale


    【解决方案1】:

    不幸的是,如果不使用包,就无法做到这一点。正如您所说,您可以使用pyicu,但如果您不想使用它,则可以对其进行硬编码:

    import re
    
    def tr_upper(word):
        word = re.sub(r"i", "İ", word)
        word = re.sub(r"ı", "I", word)
        word = re.sub(r"ç", "Ç", word)
        word = re.sub(r"ş", "Ş", word)
        word = re.sub(r"ü", "Ü", word)
        word = re.sub(r"ğ", "Ğ", word)
        word = word.upper() # for the rest use default upper
        return word
    
    print( tr_upper("istanbul") ) #İSTANBUL
    

    【讨论】:

    • 在官方 python 文档中它说:locale.LC_CTYPE¶ Locale category for the character type functions. Depending on the settings of this category, the functions of module string dealing with case change their behaviour. 但你的回答意味着 python 根本不使用LC_CTYPE。我简直不敢相信。不是你,情况。
    • 看来python无法正确处理i, İ, I, ı,是软件界非常普遍的问题。
    • @kureta:这不是 Python 的问题,因为这些东西被卸载到了操作系统。 ICU 使用自己的本地化数据库。那么你能检查一下操作系统是否安装了你的语言环境(locale -a),拼写正确,并且它可以进行这样的转换吗?
    • 更正(我之前的评论)。 Python 使用通用的 Unicode 算法。所以根据python doc“没有办法根据语言环境执行大小写转换和字符分类”,这很可惜,因为他们知道这个问题。
    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多