在Python中将字符如'³'转换为整数

4
我在我的数据集中有这个字符'³',我正在处理它。
通用的想法是检测一个字符是否是整数,将其转换为整数并在其基础上进行处理。
>>> x = '³'
>>> x.isdigit() # Returns True
True

Python检测到这个字符是一个数字。但是当我尝试转换它时,会引发以下错误。
>>> int(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '³'

我希望这些字符也能转换为整数,以便于我进一步处理。
不确定这是否有帮助,但这是我的本地信息。
>>> import locale
>>> locale.getdefaultlocale()
('en_US', 'UTF-8')

我需要知道x的值是否总是'3',如果不是,它的取值范围是什么? - undefined
我假设它应该在0-9的范围内。我知道我可以简单地将这些数字中的每一个映射为整数来进行转换。但我很好奇为什么Python会将其识别为数字却无法转换。 - undefined
检查isdigit()isdecimal()之间的区别 - undefined
因为是的,它是一个数字,但它具有不同的Unicode字符,所以它被识别为数字,但无法转换为整数。 - undefined
1
这个回答解决了你的问题吗?识别不同语言中的Unicode数字 - undefined
1个回答

6
你可以使用unicodedata和NFKC来进行转换 这里是一个详细的代码,带有一些错误处理
import unicodedata

x = '³'
try:
    regular_digit = unicodedata.normalize('NFKC', x)
    integer_value = int(regular_digit)
    print(integer_value)
except ValueError:
    print(f"'{x}' is not a convertible superscript digit.")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接