Can I call a function inside a Lambda expression in python

情到浓时终转凉″ 提交于 2021-02-10 15:52:10

问题


I have a function with including if, else condition and for loop. I want to write this function inside a lambda expression. I tried from many ways to create this lambda function. But still I couldn't do it. This is my function with another rules.

negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
  s = sentence.split()
  l = [s.index(word) for word in s if word in list2]
# Will returns list of indices (of sentence) where word is in list2
   if len(l) > 0:
    for e in l:
        # Check previous word
        if s[e-1] not in negation:
            print 'sad'

Can I express this function inside a lambda expression since I developing a rule based classifier for detect emotion from a sentence like happy, sad, angry. Following is my lambda function.

rules = [(lambda x: word_tokenize(x)[-1] == '?', "neutral"),
         (lambda x: word_tokenize(x)[0] in question, "neutral"),
         (lambda x: any(word in list2 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "sad"),
     (lambda x: any(word in list1 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "happy")]

         print classify("I miss you", rules)

回答1:


Instead of cramming everything into a lambda expression, I would just create a function that did everything you need it to do (from your comment, it sounds like you want to apply certain rules to a sentence in a certain order). You can always use that function in list comprehension, map, reduce, etc. Since I don't know exactly what your rules are though, this is the best example I can give:

a = ["This is not a sentence. That was false.", 
     "You cannot play volleyball. You can play baseball.", 
     "My uncle once ate an entire bag of corn chips! I am not lying!"]
def f(paragraph):
    sentences = paragraph.split(".")
    result = []
    for i in range(len(sentences)):
        //apply rules to sentences
        if "not" in sentences[i]:
            result.append("negative")
        else:
            result.append("positive")
    return result
my_result = [f(x) for x in a]



回答2:


Your function could use some improvement:

negation_words = {"no", "not", "never"}
sad_words = {"miss", "loss", "gone", "give", "lost"}

def count_occurrences(s, search_words, negation_words=negation_words):
    count = 0
    neg = False
    for word in s.lower().split():    # should also strip punctuation
        if word in search_words and not neg:
            count += 1
        neg = word in negation_words
    return count

print("\n".join(["sad"] * count_occurrences(s, sad_words)))


来源:https://stackoverflow.com/questions/44412042/can-i-call-a-function-inside-a-lambda-expression-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!