mchangun
mchangun

Reputation: 10362

Pass variable into function during list comprehension

I have a string text and I want to Lemmatize each word in it and put it back together as a string. I am currently doing trying to do it this way:

from nltk.stem.wordnet import WordNetLemmatizer
lmtzr = WordNetLemmatizer()
text = ' '.join[lmtzr.lemmatize(word) for word in text.split()]

but I am getting the error:

SyntaxError: invalid syntax

I think I'm not allowed to pass word into a function inside a list comprehension. I have two questions:

1) Why is this not allowed?

2) How can I do this with another method?

Thank you.

Upvotes: 0

Views: 666

Answers (1)

BrenBarn
BrenBarn

Reputation: 251598

The error is because you forgot parentheses. Either use a list comprehension and pass it to join:

text = ' '.join([lmtzr.lemmatize(word) for word in text.split()])

or just use a generator comprehension:

text = ' '.join(lmtzr.lemmatize(word) for word in text.split())

Upvotes: 4

Related Questions