2014-04-01 32 views
0
'\u00BD' # ½ 
'\u00B2' # ² 

我想了解isdecimal()和isdigit()更好,因此它对于理解unicode数值属性是必需的。我将如何看到例如上述两个unicode的数值属性。如何显示Unicodes的数值属性

回答

5

要获得包含在字符“数值”,你可以使用unicodedata.numeric() function

>>> import unicodedata 
>>> unicodedata.numeric('\u00BD') 
0.5 

使用ord() function得到整数码点,可选择地结合format()产生一个十六进制值:

>>> ord('\u00BD') 
189 
>>> format(ord('\u00BD'), '04x') 
'00bd' 

您可以使用unicodedata.category()访问角色属性,然后您需要检查文档类别:

>>> unicodedata('\u00DB') 
'No' 

其中'No' stands for Number, Other

但是,类别Lo中有一系列.isnumeric() == True字符; Python unicodedata数据库仅允许您访问常规类别,并依赖于str.isdigit(),str.isnumeric()unicodedata.digit(),unicodedata.numeric()等方法来处理其他类别。

如果您想要所有数字Unicode字符的精确列表,则规范来源为Unicode database;一系列定义整个标准的文本文件。 DerivedNumericTypes.txt file (v. 6.3.0)为您提供了一个特定数字属性的“数据库视图”;它会在顶部告诉您文件是如何从标准中的其他数据文件派生的。同上DerivedNumericValues.txt file,列出每个码点的确切数值。

+1

我认为OP希望0.5和2代码点,而不是他们的代码点。 – delnan

+0

@delnan:检查,也补充说。 –

+1

我的问题可能是错误的 - 然后我读了关于属性值Numeric_Type = Digit,Numeric_Type = Decimal,Numeric_Type = Numeric我想知道我是否可以从某个unicode点产生这个属性? – Phoenix

1

the docs明确指定方法和Numeric_Type属性之间的关系。

def is_decimal(c): 
    """Whether input character is Numeric_Type=decimal.""" 
    return c.isdecimal() # it means General Category=Decimal Number in Python 

def is_digit(c): 
    """Whether input character is Numeric_Type=digit.""" 
    return c.isdigit() and not c.isdecimal() 


def is_numeric(c): 
    """Whether input character is Numeric_Type=numeric.""" 
    return c.isnumeric() and not c.isdigit() and not c.isdecimal() 

例子:

>>> for c in '\u00BD\u00B2': 
...  print("{}: Numeric: {}, Digit: {}, Decimal: {}".format(
...   c, is_numeric(c), is_digit(c), is_decimal(c))) 
... 
½: Numeric: True, Digit: False, Decimal: False 
²: Numeric: False, Digit: True, Decimal: False 

我不知道Decimal NumberNumeric_Type=Decimal将永远是相同的。

注意:'\u00B2'不是十进制的,因为标准明确排除了上标,请参阅4.6 Numerical Value (Unicode 6.2)

+0

你给出的两个字符都不是'Decimal'。你能想出第三个例子吗? – Eric

+1

@Eric这里是[*所有*十进制数字(在python可执行文件使用的Unicode标准中)](http://ideone.com/JIaSpQ) – jfs

+0

我想我对你的'is_digit('0')如何感到困惑'是'False' – Eric