作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
输入: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/
我是一名优秀的程序员,十分优秀!