【问题标题】:Can I call a function inside a Lambda expression in python我可以在 python 的 Lambda 表达式中调用函数吗
【发布时间】:2017-06-07 11:58:56
【问题描述】:

我有一个包含 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 表达式中表达这个函数吗,因为我开发了一个基于规则的分类器来检测句子中的情绪,比如快乐、悲伤、愤怒。以下是我的 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 表达式中有另一组规则。所以我想这也包括在那个表达式中。
  • 你的意思是像lambda sentence: f(sentence)吗?
  • lambda: f("Some text")?我认为你需要提供更多关于你想要做什么的细节。
  • 我认为更重要的是你不要问自己是否可以创建一个与你的函数f 做同样事情的 lambda 函数,但如果你 应该。任何包含在 lambda 中的重要函数都变得非常难以阅读。

标签: python loops if-statement lambda


【解决方案1】:

我不会把所有东西都塞进一个 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]

【讨论】:

    【解决方案2】:

    您的功能可能需要一些改进:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-15
      • 2011-04-21
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多