[英]how to send in variables in a function in 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]
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]
sentiment_point = giving_points(index_focus_word, ">", 1, sentence, -2)
... if index_focus_word sign index_sentiment_word:
这将不起作用,因为您将“>”作为简单的String传递,而Python无法识别您打算将其作为Operator传递。
如果您的问题是二进制的(“ <”或“>”),则非常简单的解决方案是不传递String而是传递Bool值来确定要使用的运算符:
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:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.