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?

Sourav Chatterjee
  • 640
  • 1
  • 12
  • 23

2 Answers2

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
Community
  • 1
  • 1
Aran-Fey
  • 30,995
  • 8
  • 80
  • 121
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.)

deceze
  • 471,072
  • 76
  • 664
  • 811