Skip to main content
 首页 » 编程设计

python之如何在python2.7中的函数中发送变量

2025年05月04日28lonelyxmas

我正在用 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] 

请您参考如下方法:

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]