【问题标题】:Delete a string if matching with a list [duplicate]如果与列表匹配,则删除字符串[重复]
【发布时间】:2021-11-12 16:47:28
【问题描述】:

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

我试过了:

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

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

想要的输出是:

Inp = "Rockstar"

【问题讨论】:

  • 问题与artificial-intelligence无关,请不要发送无关标签(已删除)。

标签: python python-3.x string automation


【解决方案1】:

从字符串中删除空格分隔的字符串有点复杂。你必须做一些技巧来实现这一点。

步骤:

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

代码:

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

【讨论】:

    【解决方案2】:

    像这样使用 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)
    

    【讨论】:

      【解决方案3】:

      您必须遍历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):
      

      【讨论】:

      • 这不适用于问题中的示例。它将替换“youtube”,而不是“搜索 youtube”。
      • @khelwood 谢谢,我已经更新了答案以显示如何修复words 列表。
      • 对于case sensitive 字符串,您的解决方案将失败。 :)
      • @Sabil True,但没有迹象表明需要不区分大小写。如果需要,请参阅stackoverflow.com/questions/919056/case-insensitive-replace
      猜你喜欢
      • 1970-01-01
      • 2022-10-15
      • 2021-04-17
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多