如果与列表匹配则删除字符串

Delete a string if matching with a list

我想识别列表中的单词是否在输入字符串中,如果是,则删除该单词。

我试过:

words = ["youtube","search youtube","play music"]
Inp = "search youtube Rockstar"

if words in Inp:
   Inp = Inp.replace(words,"")

想要的输出是:

Inp = "Rockstar"

您必须遍历 words 列表并替换每个单词。

for word in words:
    Inp = Inp.replace(word, '')

如果words的元素有重叠,比如youtubesearch youtube,你需要把长的放在前面。否则,当 youtube 被移除时,它不会找到 search youtube 来替换它。所以让它:

words = ["search youtube","youtube","play music"]

如果你不能这样改变words,你可以在循环时对它们进行排序:

for word in sorted(words, key=len, reverse=True):

像这样使用 for 循环:

words = ["youtube","search youtube","play music"]
Inp = "search youtube Rockstar"

for word in words:
  if word in Inp:
    Inp = inp.replace(word, '')
  else:
    pass

print(Inp)

从字符串中删除 space 分隔的字符串有点复杂。你必须做一些黑客才能实现这一目标。

步骤:

  1. 首先,您必须生成一个唯一的要删除的单词列表
  2. 从字符串中删除过滤的词
  3. 根据之前生成的字符串创建一个新的单词列表
  4. 最后加入列表删除不必要的spaces

代码:

import re


def remove_matching_string(my_string, words):
    # generate an unique list of words that we want to remove
    removal_list = list(set(sum([word.split() for word in words], [])))

    # remove strings from removal list
    for word in removal_list:
        insensitive_str = re.compile(re.escape(word), re.IGNORECASE)
        my_string = insensitive_str.sub('', my_string)

    # split string after apply removal list
    my_string = my_string.split()

    # concat string to remove unnecessary space between words
    final_string = ' '.join(s for s in my_string if s)

    # return the final string
    return final_string


words = ["youtube","search youtube","play music"]
Inp = "Search youtube Rockstar Play Music On Youtube   PlAy MusIc Now"

final_string = remove_matching_string(Inp, words)
print(final_string)

输出:

Rockstar On Now