我有一个函数,包括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)
答案 0 :(得分:2)
我没有把所有内容都塞进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]
答案 1 :(得分:1)
您的功能可以使用一些改进:
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)))