Python 从列表中删除带有自定义停止词的短语
我有两张单子Python 从列表中删除带有自定义停止词的短语,python,list,Python,List,我有两张单子 listA = ['New Delhi', 'Moscow', 'Berlin', 'France', 'To Washington'] stopwordlist = ['new', 'To'] 我想得到这样的东西 finalList = ['Moscow', 'Berlin', 'France'] 如果我在寻找完整的词语,那么我迄今为止所尝试的方法是有效的: listB = [] for item in listA: if item not in stopwordli
listA = ['New Delhi', 'Moscow', 'Berlin', 'France', 'To Washington']
stopwordlist = ['new', 'To']
我想得到这样的东西
finalList = ['Moscow', 'Berlin', 'France']
如果我在寻找完整的词语,那么我迄今为止所尝试的方法是有效的:
listB = []
for item in listA:
if item not in stopwordlist:
listB.append(item)
else:
continue
....
....
return listB
我们可以拆分
项
,然后检查stopwordlist中的项。但这似乎是许多变通办法。或者我可以使用regexre.match
这里有一种方法
>>> listA = ['New Delhi', 'Moscow', 'Berlin', 'France', 'To Washington']
>>> stopwordlist = ['new', 'To']
>>> finalList = [i for i in listA if not any(j.lower() in i.lower() for j in stopwordlist)]
>>> finalList
['Moscow', 'Berlin', 'France']
或者您可以使用内置的过滤器功能
>>> listA = ['New Delhi', 'Moscow', 'Berlin', 'France', 'To Washington']
>>> stopwordlist = ['new', 'To']
>>> list(filter(lambda x: not any(j.lower() in x.lower() for j in stopwordlist), listA))
['Moscow', 'Berlin', 'France']
输出
['Moscow', 'Berlin', 'France']
['Moscow', 'Berlin', 'France']
你必须降低你的止损词,同时也要降低你的止损词:
listA = ['New Delhi', 'Moscow', 'Berlin', 'France', 'To Washington']
stopwordlist = ['new', 'To']
stop_words = {e.lower() for e in stopwordlist}
finalList = [e for e in listA if not stop_words.intersection(e.lower().split())]
或者您可以使用正则表达式:
import regex as re
stop_words_regex = re.compile(r"\L<words>", words=stop_words)
finalList = [e for e in listA if not stop_words_regex.findall(e.lower())]
所以你有一个需要删除的所有单词的列表!如果子字符串(stopword)匹配,我会查找一些内容,然后将该单词也从初始列表中删除。是否仅当该单词以字符串开头或包含该字符串时才将其删除?e、 g.如果停止字是至
您是否会将华盛顿至
删除?或者如果To
构成单词的一部分,例如Sacremento
?@Betafish这个答案怎么样?问:你为什么要用列表理解把它转换成元组?使用发电机并节省内存。TLDR:第一行中的[
和]
是对内存的浪费。@adrio是为了使用内置函数starstwith
。我的意思是避免在将其转换为元组之前将其转换为列表。删除[
和]
,它将是创建元组的生成器,而不是创建创建元组的列表的生成器。这次我讲清楚了吗?
['Moscow', 'Berlin', 'France']
listA =['New Delhi','Moscow', 'Berlin','France', 'To Washington']
stopwordlist = ['new','To']
listA = [i.lower() for i in listA]
stopwordlist = [i.lower() for i in stopwordlist]
listB =[]
for item in listA:
flag = True
for i in item.split(' '):
if i in stopwordlist:
flag =False
if flag:
listB.append(item)
print(listB)