gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:58:22 24 4
gpt4 key购买 nike

输入: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com