gpt4 book ai didi

python - 如何使用正则表达式匹配 Python 中的列表引用?

转载 作者:行者123 更新时间:2023-11-30 23:45:14 25 4
gpt4 key购买 nike

我有一个字符串列表,我需要从中删除与另一个列表中的子字符串匹配的所有元素。我正在尝试使用列表、嵌套循环和正则表达式来做到这一点。

以下代码片段的输出生成 ["We don't", "need no", "education"],而不是所需的 ["education"]。我是 Python 新手,这是我第一次尝试正则表达式,但我被语法困住了。

import re

testfile = ["We don't", "need no", "education"]
stopwords = ["We", "no"]
dellist = []

for x in range(len(testfile)):
for y in range(len(stopwords)):
if re.match(r'\b' + stopwords[y] + '\b', testfile[x], re.I):
dellist.append(testfile[x])

for x in range(len(dellist)):
if dellist[x] in testfile:
del testfile[testfile.index(dellist[x])]

print testfile

线路

if re.match(r'\b' + stopwords[y] + '\b', testfile[x], re.I):

对于循环中的所有迭代都返回“None”,所以我猜这就是我的问题所在......

最佳答案

这是因为 re.match 从字符串的开头开始测试匹配。

尝试使用re.search。另外,您在第二个 '\b' 上缺少 r:

if re.search(r'\b' + stopwords[y] + r'\b', testfile[x], re.I):
<小时/>

此外,您可以使用列表理解来构建 dellist (您可能可以使用列表理解来完全构建新的 testfile ,但它在时刻):

dellist = [w for w in testfile for test in stopwords if re.search(test,w,re.I)]
<小时/>

另一个想法 - 既然你无论如何都在使用 re 模块,为什么不将你的 stopwords 合并到 \b(We|no)\b 然后你可以针对 one 正则表达式测试 testfile 吗?

regex = r'\b(' + '|'.join(stopwords) + r')\b'  # r'\b(We|no)\b'

现在您只需查找与该正则表达式匹配的单词即可:

newtestfile = [w for w in testfile if re.search(regex,w,re.I) is None]
# newtestfile is ['education']

关于python - 如何使用正则表达式匹配 Python 中的列表引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9676821/

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