从给定的列表中找到单词并替换找到的单词

Find the word from the list given and replace the words so found

我的问题很简单,但我一直没能找到合适的解决方案。 下面是我的程序:

given_list   = ["Terms","I","want","to","remove","from","input_string"]
input_string = input("Enter String:")
if any(x in input_string for x in given_list):
     #Find the detected word
     #Not in bool format
     a = input_string.replace(detected_word,"")
     print("Some Task",a)

此处,given_list 包含我要从 input_string 中排除的字词。 现在,我面临的问题是 any() 产生了一个 bool 结果,我需要 any() 检测到的单词并将其替换为空白,以便执行一些任务。

Edit: any() function is not required at all, look for useful solutions below.

遍历 given_list 并替换它们:

for i in given_list:
    input_string = input_string.replace(i, "")
print("Some Task", input_string)

完全不需要检测:

for w in given_list:
     input_string = input_string.replace(w, "")

str.replace 如果单词不存在并且检测所需的子字符串测试无论如何都必须扫描字符串,则不会执行任何操作。

找到每个单词并替换它的问题是 python 将不得不重复遍历整个字符串。另一个问题是您会在不想要的地方找到子字符串。例如,“to”在排除列表中,因此您最终会将“tomato”更改为“ma”

在我看来,您似乎想要替换整个单词。解析是一个全新的主题,但让我们简化一下。我只是假设一切都是小写的,没有标点符号,尽管以后可以改进。让我们使用 input_string.split() 遍历整个单词。

我们想用空替换一些单词,所以让我们迭代 input_string,并使用同名的内置函数过滤掉我们不需要的单词。

exclude_list   = ["terms","i","want","to","remove","from","input_string"]
input_string = "one terms two i three want to remove"
keepers = filter(lambda w: w not in exclude_list, input_string.lower().split())
output_string = ' '.join(keepers)
print (output_string)

one two three

请注意,我们创建了一个迭代器,它允许我们只遍历整个输入字符串一次。而不是替换单词,我们基本上只是通过让迭代器不 return 来跳过我们不想要的单词。

由于过滤器需要一个函数来对是否包含或排除每个单词进行布尔检查,因此我们必须定义一个。我使用“lambda”语法来做到这一点。您可以将其替换为

def keep(word):
    return word not in exclude_list

keepers = filter(keep, input_string.split())

要回答关于 any 的问题,请使用赋值表达式 (Python 3.8+)。

if any((word := x) in input_string for x in given_list):
    # match captured in variable word