python - 为什么 "\p{L}"在此正则表达式中不起作用?

标签 python regex unicode jython

操作系统:Windows 7。Jython 2.7.0“最终版本”。

for token in sorted_cased.keys():
    freq = sorted_cased[ token ]
    if freq > 1:
        print( 'token |%s| unicode? %s' % ( token, isinstance( token, unicode ), ) )
        if re.search( ur'\p{L}+', token ):
            print( '  # cased token |%s| freq %d' % ( token, freq, ))

sorted_cased 是一个显示标记出现频率的字典。在这里,我试图清除出现频率 > 1 的单词(仅限 unicode 字符)。(注意,我使用的是 re.match 而不是 searchsearch 应该检测事件 1,例如 token 中的\p{L})

示例输出:

token |Management| unicode? True
token |n| unicode? True
token |identifiés| unicode? True
token |décrites| unicode? True
token |agissant| unicode? True
token |tout| unicode? True
token |sociétés| unicode? True

没有人认识到它里面有一个[p{L}]。我尝试了各种排列:双引号、添加 flags=re.UNICODE 等。

稍后 我被要求解释为什么这不能被归类为 How to implement \p{L} in python regex 的重复项。它可以,但是......其他问题的答案并没有引起人们注意使用REGEX MODULE(旧版本?非常新版本?注意它们是不同的)而不是<强>RE模块。为了拯救 future 遇到这个问题的人的毛囊和理智,我请求允许保留本段,尽管这个问题是“欺骗”的。

我还尝试安装 Pypi 正则表达式模块在 JYTHON 下失败(使用 pip)。使用 java.util.regex 可能更好。

最佳答案

如果您有权访问 Java java.util.regex,最好的选择是使用内置的 \p{L} 类。

Python(包括 Jython 方言)不支持 \p{L} 和其他 Unicode 类别类。也不是 POSIX 字符类。

另一种替代方法是限制 \w 类,例如 (?![\d_])\w 并使用 UNICODE 标志。 If UNICODE is set, this \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. 。这种替代方案有一个缺陷:它不能在字符类中使用。

另一个想法是使用 [^\W\d_] (带有 re.U 标志)来匹配任何不是非单词的字符(\W)、数字(\d) 和_ 字符。它将有效匹配任何 Unicode 字母

关于python - 为什么 "\p{L}"在此正则表达式中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117207/

相关文章:

维护签名的 Python 装饰器,允许修改文档字符串,并允许可选参数

python - 使用预测图像和地面真实图像评估神经网络

c# - 寻找正则表达式以大写为基础拆分字符串

javascript - 正则表达式从头开始删除哈希

unicode - 如何检测非规范化的 unicode 字符?

Python 请求 - 重定向后的身份验证

python - 如何查找输入中的列表数? (Python)

regex - 正则表达式 - 读取直到第一次遇到冒号 ( :) and ignoring the rest of the line and the number part in the beginning

C# Unicode(日语字符)

python - 如何使用 Python 反转 Unicode 分解?