我可以在python中的Lambda表达式内调用函数吗 [英] Can I call a function inside a Lambda expression in python
问题描述
我有一个包含if,else条件和for循环的函数.我想在lambda表达式中编写此函数.我尝试了多种方法来创建此lambda函数.但是我还是做不到.这是我的另一个规则.
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'
我可以在lambda表达式中表达此功能吗,因为我开发了基于规则的分类器来从快乐,悲伤,愤怒之类的句子中检测情绪.以下是我的lambda函数.
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)
推荐答案
我只是创建一个函数来完成您需要做的所有事情(从您的评论中听起来像您想要的),而不是将所有内容塞入lambda表达式中.以一定的顺序对句子应用某些规则).您始终可以在列表理解,映射,归约等方式中使用该函数.由于我不知道您的规则到底是什么,所以这是我可以提供的最佳示例:
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]
这篇关于我可以在python中的Lambda表达式内调用函数吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!