我想从一个句子中摘录一个完整的单词. 多亏了this answer

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

在这样的情况下,我可以得到完整的单词:

findWholeWord('thomas')('this is Thomas again')   # -> <match object>
findWholeWord('thomas')('this is,Thomas again')   # -> <match object>
findWholeWord('thomas')('this is,Thomas, again')  # -> <match object>
findWholeWord('thomas')('this is.Thomas, again')  # -> <match object>
findWholeWord('thomas')('this is ?Thomas again')  # -> <match object>

单词旁边的符号就不用费心了.

然而,如果有一个数字,它就找不到这个词.

我应该如何修改表达式以匹配单词旁边有数字的大小写?喜欢:

findWholeWord('thomas')('this is 9Thomas, again')
findWholeWord('thomas')('this is9Thomas again')
findWholeWord('thomas')('this is Thomas36 again')

推荐答案

可以使用regexp (?:\d|\b){0}(?:\d|\b)将目标单词与单词边界或其两侧的数字进行匹配.

import re

def findWholeWord(w):
    return re.compile(r'(?:\d|\b){0}(?:\d|\b)'.format(w), flags=re.I).search

for s in [
    'this is Thomas again',
    'this is,Thomas again',
    'this is,Thomas, again',
    'this is.Thomas, again',
    'this is ?Thomas again',
    'this is 9Thomas, again',
    'this is9Thomas again',
    'this is Thomas36 again',
    'this is -Thomas- again',
    'athomas is no match',
    'thomason no match']:
    print("match >" if findWholeWord('thomas')(s) else "*no match* >", s)

Output:

match > this is Thomas again
match > this is,Thomas again
match > this is,Thomas, again
match > this is.Thomas, again
match > this is ?Thomas again
match > this is 9Thomas, again
match > this is9Thomas again
match > this is Thomas36 again
match > this is -Thomas- again
*no match* > athomas is no match
*no match* > thomason no match

如果您想对多个输入或在循环中重复使用相同的目标单词,那么您可以将findWholeWord()调用赋给一个变量,然后调用它.

matcher = findWholeWord('thomas')
print(matcher('this is Thomas again'))
print(matcher('this is,Thomas again'))

Python相关问答推荐

用Python获取HTML Span类中的数据

剧作家Python没有得到回应

具有多个选项的计数_匹配

@Property方法上的inspect.getmembers出现意外行为,引发异常

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

如何在Windows上用Python提取名称中带有逗号的文件?

在Python中管理打开对话框

Julia CSV for Python中的等效性Pandas index_col参数

ODE集成中如何终止solve_ivp的无限运行

在Django admin中自动完成相关字段筛选

UNIQUE约束失败:customuser. username

使用Python和文件进行模糊输出

为什么\b在这个正则表达式中不解释为反斜杠

dask无groupby(ddf. agg([min,max])?''''

OpenCV轮廓.很难找到给定图像的所需轮廓

为什么在FastAPI中创建与数据库的连接时需要使用生成器?

如何使用正则表达式修改toml文件中指定字段中的参数值

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

有没有办法让Re.Sub报告它所做的每一次替换?

Python OPCUA,modbus通信代码运行3小时后出现RuntimeError