【发布时间】: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