我有以下 list :

dirtylist = ["lemons zested", "grated cheddar cheese", "carrots, thinly chopped"]

以下是我要从列表中的每个字符串项中删除的单词列表:

bannedWord = ['grated', 'zested', 'thinly', 'chopped', ',']

我try 生成的结果列表如下:

cleaner_list = ["lemons", "cheddar cheese", "carrots"]

到目前为止,我还无法做到这一点.我的try 如下:

import re

dirtylist = ["lemons zested", "grated cheddar cheese", "carrots, thinly chopped"]
cleaner_list = []
    
def RemoveBannedWords(ing):
    pattern = re.compile("\\b(grated|zested|thinly|chopped)\\W", re.I)
    return pattern.sub("", ing)
    
for ing in dirtylist:
    cleaner_ing = RemoveBannedWords(ing)
    cleaner_list.append(cleaner_ing)
    
print(cleaner_list)

这将返回:

['lemons zested', 'cheddar cheese', 'carrots, chopped']

我也try 过:

import re

dirtylist = ["lemons zested", "grated cheddar cheese", "carrots, thinly chopped"]
cleaner_list = []

bannedWord = ['grated', 'zested', 'thinly', 'chopped']
re_banned_words = re.compile(r"\b(" + "|".join(bannedWord) + ")\\W", re.I)

def remove_words(ing):
    global re_banned_words
    return re_banned_words.sub("", ing)

for ing in dirtylist:
    cleaner_ing = remove_words(ing)
    cleaner_list.append(cleaner_ing)
  
print(cleaner_list)

这将返回:

['lemons zested', 'cheddar cheese', 'carrots, chopped']

在这一点上,我有点迷茫,不确定我错在哪里.任何帮助都是非常感激的.

推荐答案

一些问题:

  • 在您的正则表达式requires中的最后\W表示有一个字符跟随在被禁止的单词之后.因此,如果禁用的单词是输入字符串中的最后一个单词,则该操作将失败.您可以再次使用\b,就像您在regex开始时所做的那样

  • 由于您还想替换逗号,因此需要将其添加为一个选项.请确保不要将其放在同一捕获组中,因为如果在末尾加上\\b,则需要在逗号后面跟一个字母数字字符.因此,它应该作为一个选项放在您的正则表达式的最后(或开始).

  • 您可能希望对生成的字符串调用.strip(),以删除删除禁用单词后剩余的所有空格.

就这样.

def RemoveBannedWords(ing):
    pattern = re.compile("\\b(grated|zested|thinly|chopped)\\b|,", re.I)
    return pattern.sub("", ing).strip()

Python相关问答推荐

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

如何使用它?

提取相关行的最快方法—pandas

未知依赖项pin—1阻止conda安装""

Python逻辑操作作为Pandas中的条件

需要帮助重新调整python fill_between与数据点

在Python 3中,如何让客户端打开一个套接字到服务器,发送一行JSON编码的数据,读回一行JSON编码的数据,然后继续?

Python全局变量递归得到不同的结果

幂集,其中每个元素可以是正或负""""

以逻辑方式获取自己的pyproject.toml依赖项

Python Pandas—时间序列—时间戳缺失时间精确在00:00

Python pint将1/华氏度转换为1/摄氏度°°

如何在Gekko中使用分层条件约束

将CSS链接到HTML文件的问题

在Django中重命名我的表后,旧表中的项目不会被移动或删除

如何在PythonPandas 中对同一个浮动列进行逐行划分?

Django在一个不是ForeignKey的字段上加入'

如何防止html代码出现在quarto gfm报告中的pandas表之上

VSCode Pylance假阳性(?)对ImportError的react

按最大属性值Django对对象进行排序