gpt4 book ai didi

python - 通过尝试使用 "|"连接单词来使用正则表达式查找文本中单词列表的所有出现位置无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 21:51:19 25 4
gpt4 key购买 nike

我需要使用正则表达式查找文本中出现的所有单词列表。例如,给出以下单词:

words = {'i', 'me', 'my'}

还有一些

text = 'A book is on the table. I have a book on the table. My book is on the table. There is my book on the table.'

应该返回result = ["I", "My", "my"]

我正在使用这个:

re.findall(r"'|'.join(words))", text,flags=re.IGNORECASE))

但它返回一个空列表。

如果我使用这个:

re.findall(r"(?=("+'|'.join(words)+r"))", text, flags=re.IGNORECASE))

返回:

['i', 'I', 'My', 'i', 'i', 'my']

这是不正确的。

最佳答案

这就是我要做的:

此正则表达式将从我的列表中获取值,这些值前面或后面不能有任何单词,例如:是我吗?

import re

words = ["I", "am", "my"]
text = "A book is on the table. I have a book on the table. My book is on the table. There is my book on the table."

pattern = r'\W.*?({})\W.*?'.format('|'.join(words))
s = re.findall(pattern, text, flags=re.IGNORECASE)
print(s)

关于python - 通过尝试使用 "|"连接单词来使用正则表达式查找文本中单词列表的所有出现位置无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60129620/

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