noun_gathering_system = [(lemmatizer.lemmatize(word), 1) if tag.pos_tag([word])[0][1] in ["NN", "NNS", "NNP", "NNPS", "FW"] else (lemmatizer.lemmatize(word), 2) if tag.pos_tag([word])[0][1] in ["PRP"] else (lemmatizer.lemmatize(word), 3) if tag.pos_tag([word])[0][1] in ["JJ"] else continue for word in word_tokenize(sentence.lower())]
Using nltk, I am attempting to gather only certain nouns and word from a sentence. I want to prioritize the words I collect by Noun-1, Pronoun-2, Adjective-3. The code works fine when written without list comprehension, but with list comprehension, my code keeps failing with the following error.
File "main.py", line 16
validitychecker = [(lemmatizer.lemmatize(word), 1) if tag.pos_tag([word])[0][1] in ["NN", "NNS", "NNP", "NNPS", "FW"] else (lemmatizer.lemmatize(word), 2) if tag.pos_tag([word])[0][1] in ["PRP"] else (lemmatizer.lemmatize(word), 3) if tag.pos_tag([word])[0][1] in ["JJ"] else pass for word in word_tokenize(sentence.lower())]
^
SyntaxError: invalid syntax
I'm not sure why the syntax is wrong and any help would be great.
Sure, here is a fizzbuzz using list comprehension. It is terrible to read and anyone reading it will hate you. For complex if/else stuff, write a standard loop.
['Fizzbuzz' if x%3==0 and x%5==0 else 'Fizz' if x%3==0 else 'Buzz' if x%5==0 else x for x in range(1,101)]
The best answer in my opinion here would be @dfundako's because when it comes to complex if/else stuff, it is much easier to just write a standard loop. However, if you really want to keep it as a list comprehension, your only mistake here is the pass
statement, which you can replace with None
like this:
validitychecker = [(lemmatizer.lemmatize(word), 1) if tag.pos_tag([word])[0][1] in ["NN", "NNS", "NNP", "NNPS", "FW"] else (lemmatizer.lemmatize(word), 2) if tag.pos_tag([word])[0][1] in ["PRP"] else (lemmatizer.lemmatize(word), 3) if tag.pos_tag([word])[0][1] in ["JJ"] else None for word in word_tokenize(sentence.lower())]
Then, you can simply do list(filter(None, validitychecker))
to remove all the None
in the list.
Hope this helps!
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.