当前位置: 欣欣网 > 码农

出乎意料:怎么中文也属于字母?

2024-03-18码农

来源:未闻Code

我最近在使用一个第三方库,叫做 RapidFuzz 。它有一个工具函数,叫做 utils.default_process ,在官方文档里面,是这样介绍的:

红色方框里面说,这个函数可以移除所有的非 alphanumeric 字符。如果我们使用翻译软件,会发现 alphanumeric 的意思是字母和数字。如下图所示:

因此,我想当然觉得,这个功能函数,只会保留26个英文字母的大小写加上10个数字,一共62个字符。把除此之外的所有其他字符都移除掉。

但我经过测试,它竟然没有办法过滤掉中文字符,如下图所示。难道终于也属于字母?

于是我到Github上面去给这个项目提Issue。但作者却说这个函数没有问题,并且使用Python的 .isalnum() 来做测试,发现Python也会认为中文也是 alphanumeric 。如下图所示:

这就非常奇怪了,于是我找到Python官方文档,发现它是这样说的:

str.isalnum() [1]

Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. A character c is alphanumeric if one of the following returns True : c.isalpha() , c.isdecimal() , c.isdigit() , or c.isnumeric() .

说明 '中文'.isalnum() 返回 True ,显然是因为 '中文'.isalpha() 返回了 True 。而之所以 .isalpha() 会返回 True ,是因为它判断的不仅仅是英文字母,而是所有Unicode里面,类别为 letter 的字符:

str.isalpha() [2]

Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as 「Letter」, i.e., those with general category property being one of 「Lm」, 「Lt」, 「Lu」, 「Ll」, or 「Lo」.

在Unicode标准网站 UAX #44: Unicode Character Database [3] 上面,可以看到它这里定义的 Lm Lt Lu Ll Lo 的意思:

我们使用Python自带的 unicodedata 模块,可以看到中文字符的类型,确实是 Lo ,如下图所示:

所以, '中文'.isalpha() 返回 True 确实是合理的。

以后看到 alphanumeric ,再也不要以为只有62个字符了。

参考资料

[1]

Link to this definition: https://docs.python.org/3/library/stdtypes.html#str.isalnum

[2]

Link to this definition: https://docs.python.org/3/library/stdtypes.html#str.isalpha

[3]

UAX #44: Unicode Character Database: https://unicode.org/reports/tr44/#General_Category_Values


以上是今天分享的内容。提醒一下,Python猫 的赠书【流畅的Python】活动仍在进行,不要错过啦!-->

图书购买链接