繁体   English   中英

拆分单词后,从列表中删除单词:Python

[英]removing words from a list after splitting the words :Python

我有一个清单

List = ['iamcool', 'Noyouarenot'] 
stopwords=['iamcool']

我要做的是从列表中删除stowprds。 我正在尝试通过以下脚本来实现

query1=List.split()
resultwords  = [word for word in query1 if word not in stopwords]
result = ' '.join(resultwords)
return result

所以我的结果应该是

result =['Noyouarenot']

我收到一个错误

AttributeError: 'list' object has no attribute 'split'

这也是正确的,我缺少什么小东西,请帮忙。 感谢您的帮助。

列表理解和条件检查stopwords隶属度。

print [item for item in List if item not in stopwords]

filter

print filter(lambda item: item not in stopwords, List)

set操作,您可以在此处参考我有关速度差异的答案。

print list(set(List) - set(stopwords))

输出-> ['Noyouarenot']

这是修复您的错误的代码段:

lst = ['iamcool', 'Noyouarenot']
stopwords = ['iamcool']

resultwords = [word for word in lst if word not in stopwords]
result = ' '.join(resultwords)
print result

假设您的输入列表和停用词列表不关心顺序和重复项的另一种可能的解决方案:

print " ".join(list(set(lst)-set(stopwords)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM