python - 如何查找带下标的单词?

标签 python regex python-3.x

输入:s = "test1 this is a sample subscript o₁"

我试过:re.compile(r'\b[^\W\d_]{2,}\b').findall(s)

它找到超过 2 个字符且不包含数字的单词 'this', 'is', 'sample', 'subscript', 'o₁',

但还是有下标号。

有没有办法去除其中包含下标的单词?

期望输出:'this', 'is', 'sample', 'subscript'

最佳答案

重点是 Python 3 正则表达式中的 Unicode 感知 \d 不匹配 No Unicode category .

如果您只需要使用 ASCII 字母单词,请使用

r'\b[a-zA-Z]{2,}\b'

或者,使用 re.A/re.ASCII 标记使模式不支持 Unicode:

re.compile(r'\b[^\W\d_]{2,}\b', re.A)

参见 this Python 3 demo .

如果您需要使用任何 Unicode 字母,您可以通过将所有 No 字符添加到正则表达式否定字符类(这可能使它成为一个乏味的解决方案)来修复它,或者添加一个程序找到匹配项后检查匹配项是否包含 No 类别中的任何字符。

参见 this Python 3 demo :

import re, sys, unicodedata
s = "test1 this is a sample subscript o₁"
No = [chr(i) for i in range(sys.maxunicode) if unicodedata.category(chr(i)) == 'No']
print([x for x in re.findall(r'\b[^\W\d_]{2,}\b', s) if not any(y in x for y in No)])
# => ['this', 'is', 'sample', 'subscript']

确保您使用的是最新的 Python 版本以支持最新的 Unicode 标准,或者依赖 PyPi regex module :

p = regex.compile(r"\b\p{L}{2,}\b")
print(p.findall(s))

关于python - 如何查找带下标的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108969/

相关文章:

c# - 自动为文本框中的每一行编号

python-3.x - 按降序对两列最频繁的组合进行排序

python - 单击和 pylint

python - pyodbc - ODBC 连接不工作

python - 创建中断 (ISR) 以创建平滑的机械臂运动

python - 替换 XML 文件中的 python 字符串

Java/Hive 正则表达式解释

javascript - ACE 编辑器多行正则表达式

python - 从 Python2 到 Python3 时的 b64encode

python - Python中的Pyo;名称 'Server' 未定义