2017-06-07 5 views
1

if、else condition、forループを含む関数があります。この関数をラムダ式の中に記述したいと思います。私はこのラムダ関数を作るために多くの方法から試みました。しかし、まだ私はそれをすることができませんでした。これは私の別のルールによる機能です。Pythonのラムダ式の中で関数を呼び出すことはできますか?

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' 

私は、幸せな悲しい、怒ったような文から感情を検出するためのルールに基づく分類器を開発して以来、ラムダ式内でこの機能を表現することができます。以下は私のラムダ機能です。代わりに、ラムダ式にすべてを詰め込むの

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

ルールベースの分類子を開発しました。ラムダ式の中に別のルールセットがあります。ですから、私はこれにその表現にも含めたいと思います。 –

+0

'' lambda sentence:f(sentence) 'のような意味ですか? – MSeifert

+0

'lambda:f(" Some text ")'?私はあなたがしようとしていることについてより詳細に説明する必要があると思います。 – Carcigenicate

答えて

2

、私はちょうどあなたがそれはあなたのコメントから(行うために必要なすべてをした機能を作成し、それはあなたが特定の文章に特定のルールを適用したいように聞こえます注文)。

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

あなたの関数がいくつかを使用することができます:あなたはいつも私はあなたのルールはいえいる内容を正確に把握していないので、これは私が与えることができる最良の例であるなど、、リスト内包でマップをその関数を使用する減らすことができます改善:

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))) 
関連する問題