简体   繁体   中英

Lambda expression in Python doesn't work correctly

I tried to make some lambda expressions. There is no any error. But it doesn't work correctly. Following is my code.

from nltk.tokenize import word_tokenize

list1 = 'gain, archive, win, success'.split(',')
list2 = 'miss, loss, gone, give up'.split(',')

def classify(s, rls):
for (f, emotion) in rls:
  if f(s):
     return emotion
return "another"

rules = [(lambda x: (i for i, j in zip(word_tokenize(x),list2) if i == j) != [], "sad"),
         (lambda x: (a for a, b in zip(word_tokenize(x),list1) if a == b) != [], "happy"),]

print classify("I win the game", rules)
print classify("I miss you", rules)

The output is

sad
sad

I have no idea what is the wrong with my code. Can someone help me !

Zip iterates through the lists " in parallel ", so it returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. ( source )

So you were trying to check if the i-th word of the sentence matches the i-th sentiment word in the least, which I guess is not what you want. Plus, as noted by @juanpa.arrivillaga, you were checking if a generator was equal to the empty list , which is always True , for the simple reason that a generator is not a list, independently from its content.
What you want is checking if any word in the sentence is in the sentiment list.

Try changing:

lambda x: (i for i, j in zip(word_tokenize(x),list2) if i == j) != []

to:

lambda x: any(word in list2 for word in word_tokenize(x))

So overall you define rules like this:

rules = [(lambda x: any(word in list2 for word in word_tokenize(x)), "sad"),
         (lambda x: any(word in list1 for word in word_tokenize(x)), "happy")]

Also, there are white spaces in the words in sentiment lists that can make the comparison fail. Redefine them as follows:

list1 = 'gain,archive,win,success'.split(',')
list2 = 'miss,loss,gone,give up'.split(',')

Or even better use strip to remove empty spaces from beginning and end of words as general good practice when working with strings.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM