简体   繁体   中英

removing words from a list after splitting the words :Python

I have a list

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

What I want to do is to remove stowprds from my list. I am trying to acheive this with following script

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

So my result should be

result =['Noyouarenot']

I am receiving an error

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

which is right also, what small thing I am missing, please help. I appreciate every help.

A list comprehension with a condition checking for membership in stopwords .

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

or filter

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

or set operations, you can refer to my answer on speed differences here .

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

Output -> ['Noyouarenot']

Here's the snippet fixing your error:

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

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

Another possible solution assuming your input list and stopwords list don't care about order and duplicates:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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