[英]Can I call a function inside a Lambda expression in python
I have a function with including if, else condition and for loop. 我有一个函数,包括if,else条件和for循环。 I want to write this function inside a lambda expression.
我想在lambda表达式中编写这个函数。 I tried from many ways to create this lambda function.
我试过很多方法来创建这个lambda函数。 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. 我可以在lambda表达式中表达这个函数,因为我开发了一个基于规则的分类器,用于从快乐,悲伤,愤怒等句子中检测情绪。 Following is my lambda function.
以下是我的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)
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). 我没有把所有内容都填充到lambda表达式中,而是创建一个函数来完成你需要做的所有事情(从你的评论中,听起来你想要按照特定顺序将某些规则应用于句子)。 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]
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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.