【问题标题】:How to convert unusual unicode string with number to integer in python如何在python中将带有数字的异常unicode字符串转换为整数
【发布时间】:2018-12-11 07:12:54
【问题描述】:

我有一些相当多毛的 unicode 字符串,其中包含我想测试其值的数字。通常,我只会使用str.isnumeric 来测试它是否可以通过int() 进行转换,但我遇到了isnumeric 返回Trueint() 引发异常的情况。

这是一个示例程序:

>>> s = '⒍'
>>> s.isnumeric()
True
>>> int(s)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '⒍' 

Unicode 总是充满惊喜,所以我很高兴能够对这种情况保持稳健并使用 try/except 块来捕获异常数字。但是,如果我仍然可以将它们转换为整数,我会更高兴。有没有一致的方法来做到这一点?

【问题讨论】:

    标签: python python-3.x numbers int python-unicode


    【解决方案1】:

    如果要测试是否可以将字符串传递给int,请使用str.isdecimalstr.isnumericstr.isdigit 都包含与 int 不兼容的类小数字符。

    正如 @abarnert 在 cmets 中提到的,测试字符串是否可以传递给 int 的最有保证的方法是简单地在 try 块中进行。

    另一方面,'⒍' 可以在 unicodedata 模块的帮助下转换为实际数字,例如

    print(unicodedata.digit('⒍'))
    

    将输出6

    【讨论】:

    • 这很有帮助,但是知道如何将 转换为整数甚至浮点数吗?
    • 使用unicodedataprint(unicodedata.digit('⒍')) 输出 6.
    • @blhsing 您应该将该评论添加到答案中。而且,测试是否可以将字符串传递给int最佳 方法是将其传递给try: 块中的int
    • @abarnert 确实如此。我已按照建议编辑了答案。谢谢。
    【解决方案2】:

    我不知道你会有多少运气,但 unicodedata 可能会处理一些情况(python 3 代码):

    >>> import unicodedata
    >>> unicodedata.normalize('NFKC', '⒍')
    '6.'
    

    稍微好一点。至于测试,如果你想要一个 int,你可以 int() 它并捕获异常。

    【讨论】:

    • 这行得通,因为 (DIGIT SIX FULL STOP) 分解成6 (DIGIT SIX) 和. (FULL STOP),这有点巧合地被解释为@987654328 @,但这不是所有非小数的数字/数字字符的通用解决方案。
    【解决方案3】:

    确定字符串是否可以转换为 int 的最佳方法是 try it:

    s = '⒍'
    try:
        num = int(s)
    except ValueError:
        # handle it
    

    当然,您可以尝试找出正确的方法来提前测试字符串,但为什么呢?如果您想要的规则是“无论int 接受什么”,只需使用int


    如果您想转换数字而非小数,请使用unicodedata 模块:

    s = '⒍'
    num = unicodedata.digit(s) # 6
    num = unicodedata.numeric(s) # 6.0
    num = unicodedata.decimal(s) # ValueError: not a decimal
    

    尽管Number, Other 而不是Number, Decimal Digit(因此与int 不兼容),数据库中的DIGIT SIX FULL STOP 字符条目具有数字和数字值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 2017-02-19
      • 2019-10-20
      • 2023-03-31
      • 2023-03-16
      相关资源
      最近更新 更多