我可以在python中调用Lambda表达式中的函数吗

我可以在python中调用Lambda表达式中的函数吗,python,loops,if-statement,lambda,Python,Loops,If Statement,Lambda,我有一个包含if、else条件和for循环的函数。我想在lambda表达式中编写这个函数。我尝试了多种方法来创建这个lambda函数。但我还是做不到。这是我的函数,还有另一个规则 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、else条件和for循环的函数。我想在lambda表达式中编写这个函数。我尝试了多种方法来创建这个lambda函数。但我还是做不到。这是我的函数,还有另一个规则

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'

我可以在lambda表达式中表达这个函数吗?因为我开发了一个基于规则的分类器,用于从诸如happy、sad、angry之类的句子中检测情感。下面是我的lambda函数

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)

我不想把所有的东西都塞进lambda表达式中,我只想创建一个函数来完成所有需要它做的事情(从你的评论来看,听起来你想按照一定的顺序对一个句子应用一定的规则)。您可以在列表理解、映射、减少等中始终使用该函数。因为我不知道您的规则是什么,这是我能给出的最好的示例:

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]

您的功能需要一些改进:

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)))

我正在开发一个基于规则的分类器。在lambda表达式中有另一组规则。所以我想把它也包括在这个表达式中。你的意思是像
lambda句子:f(句子)
lambda:f(“一些文本”)
?我认为您需要提供更多关于您正在尝试执行的操作的详细信息。我认为对您来说,更重要的是不要问自己是否可以创建一个lambda函数,该函数与您的函数
f
执行相同的操作,而是您是否应该这样做。任何包装在lambda中的非平凡函数都变得非常难以读取。