0

I am relatively new to python. I am trying to filter data in List using a Lambda, but the compiler gives me a syntax error for the commented code.

# documents = [(list(filter(lambda w:w if not  w in stop_words,movie_reviews.words(fileid))),category)
#         for category in movie_reviews.categories()
#         for fileid in movie_reviews.fileids(category)]
#
documents = [(list(movie_reviews.words(fileid)),category)
        for category in movie_reviews.categories()
        for fileid in movie_reviews.fileids(category)]

The uncommented section works, but the commented section gives a syntax error. Any inputs what i am doing wrong here?

2 Answers 2

2

The problem is here:

w if not w in stop_words

This is the first half of a ternary condition operator, but it's missing the else block.

You actually don't need this operator at all, your lambda should look like this:

lambda w:not w in stop_words
Sign up to request clarification or add additional context in comments.

Comments

1

x if y expressions require an else. It's an expression which must return a value, and without else it's undefined what's supposed to happen in the event that the if condition does not apply.

At the very least you need:

w if w not in stop_words else None

(Also x not in is the preferred direct operation as opposed to not x in.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.