从python中的文本列表中删除短语列表
我试图删除列表中的特定单词。假设我有以下示例:从python中的文本列表中删除短语列表,python,recursion,Python,Recursion,我试图删除列表中的特定单词。假设我有以下示例: a= ['you are here','you are there','where are you','what is that'] b = ['you','what is'] 所需输出应如下所示: ['are here', 'are there', 'where are', 'that'] 我为该任务创建了以下代码: import re def _find_word_and_remove(w,strings): """ w:
a= ['you are here','you are there','where are you','what is that']
b = ['you','what is']
所需输出应如下所示:
['are here', 'are there', 'where are', 'that']
我为该任务创建了以下代码:
import re
def _find_word_and_remove(w,strings):
"""
w:(string)
strings:(string)
"""
temp= re.sub(r'\b({0})\b'.format(w),'',strings).strip()# removes word from string
return re.sub("\s{1,}", " ", temp)# removes double spaces
def find_words_and_remove(words,strings):
"""
words:(list)
strings:(list)
"""
if len(words)==1:
return [_find_word_and_remove(words[0],word_a) for word_a in strings]
else:
temp =[_find_word_and_remove(words[0],word_a) for word_a in strings]
return find_words_and_remove(words[1:],temp)
find_words_and_remove(b,a)
>>> ['are here', 'are there', 'where are', 'that']
通过使用递归来完成这项任务,我似乎把“事情”复杂化了。有没有更简单易读的方法来完成此任务?您可以使用列表理解:
def find_words_and_remove(words, strings):
return [" ".join(word for word in string.split() if word not in words) for string in strings]
只有当b
中只有一个单词时,这才有效,但由于您的编辑和注释,我现在知道您确实需要\u find\u word\u and\u remove()
。您的递归方式并不太糟糕,但如果您不想要递归,请执行以下操作:
def find_words_and_remove(words, strings):
strings_copy = strings[:]
for i, word in enumerate(words):
for string in strings:
strings_copy[i] = _find_word_and_remove(word, string)
return strings_copy
简单的方法是使用正则表达式:
import re
a= ['you are here','you are there','where are you','what is that']
b = ['you','what is']
给你:
def find_words_and_remove(b,a):
return [ re.sub("|".join(b), "", x).strip() if len(re.sub("|".join(b), "", x).strip().split(" ")) < len(x.split(' ')) else x for x in a ]
find_words_and_remove(b,a)
>> ['are here', 'are there', 'where are', 'that']
def find_words_和_remove(b,a):
返回[re.sub(“|”).join(b),“”,x.strip(),如果len(re.sub(“|”).join(b),“”,x.strip().split(“”)>[“在这儿”、“在那儿”、“在哪儿”、“那个”]
你的代码和所有东西都有效吗?是的,有效。我用完整的例子编辑了我的问题。虽然我在标题中说“短语”,但在例子中我不清楚。对不起。单词也可以是短语。我对我的示例进行了编辑,以使其更加清晰。@MpizosDimitris:我用不同的解决方案编辑了我的答案。据我测试,是的。您是否发现了一个不起作用的示例?w
和strings
都是字符串类型。我认为strings
是一个列表。我会在一分钟内编辑它。我不确定你是否注意到了,但我确实编辑了那个解决方案。那b=['yo']
呢??它是关于删除单词或短语的。不是字符串。@MpizosDimitris如果你是对的,我想不起来,现在它应该可以工作了。