Manu Sharma
Manu Sharma

Reputation: 1739

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.

Upvotes: 0

Views: 91

Answers (2)

ospahiu
ospahiu

Reputation: 3525

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']

Upvotes: 3

BPL
BPL

Reputation: 9863

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)))

Upvotes: 1

Related Questions