2016-04-23 2 views
1

私はPython2.7で書いています。指示を呼び出すときに送る変数を ">"作る方法を理解する必要があります。この関数を何回か呼び出す必要があり、時には "<"になる必要があります。Python2.7の関数で変数を送る方法

sentiment_point = giving_points(index_focus_word, 1, sentence, -2) 

def giving_points(index_focus_word, index_sentiment_word, sentence, location): 
    if index_focus_word > index_sentiment_word: 
     sentiment_word = sentence[index_focus_word + location] 

私がしたいことを以下に示してみましたが、動作しません。

sentiment_point = giving_points(index_focus_word, ">", 1, sentence, -2) 

def giving_points(index_focus_word, sign, index_sentiment_word, sentence, location): 
    if index_focus_word sign index_sentiment_word: 
     sentiment_word = sentence[index_focus_word + location] 
+0

コードをハイライト表示し、インラインエディタの上部にある「{}」を押してコードをフォーマットしてください。 – Oisin

答えて

1
sentiment_point = giving_points(index_focus_word, ">", 1, sentence, -2) 
... if index_focus_word sign index_sentiment_word: 

あなたが渡しているので、これは、動作しません「>」単純な文字列やPythonなど、あなたがオペレータとしてそれを渡すために意図している認識しません。

あなたの問題は、非常にシンプルなソリューションを使用する事業者を決定するための文字列ではありませんが、ブール値を渡すために、だろう(「<」または 『>』)バイナリの場合:

sentiment_point = giving_points(index_focus_word, True, 1, sentence, -2) 

def giving_points(index_focus_word, greater, index_sentiment_word, sentence, location): 
    if greater: 
     if index_focus_word > index_sentiment_word: 
      sentiment_word = sentence[index_focus_word + location] 
     else: #.... 
    else: 
     if index_focus_word < index_sentiment_word: 
4

operatorモジュールは、Python演算子を実装する関数を提供します。この場合、operator.gtが必要です。

import operator 
sentiment_point = giving_points(index_focus_word, operator.gt, 1, sentence, -2) 

def giving_points(index_focus_word, cmp, index_sentiment_word, sentence, location): 
    if cmp(index_focus_word, index_sentiment_word): 
     sentiment_word = sentence[index_focus_word + location] 
+0

これは完璧です、ありがとうございます@chepner –

関連する問題