Python 使用字符串调用函数

Python 使用字符串调用函数,python,python-2.7,nodebox-linguistics,Python,Python 2.7,Nodebox Linguistics,我找不到一个能给出动词所有时态的方法。调用每个函数只有一种方法:使用动词对象替换列表中的空格。我怎样才能做到这一点 输入:argue。输出应该是:辩论,辩论,辩论。您可以为每个时态名称创建名称/参数列表。例如: from en import verb print verb.tenses() print verb.infinitive('argue') ['infinitive', 'present participle', 'past plural', '2nd singular prese

我找不到一个能给出动词所有时态的方法。调用每个函数只有一种方法:使用动词对象替换列表中的空格。我怎样才能做到这一点


输入:
argue
。输出应该是:
辩论
辩论
辩论

您可以为每个时态名称创建名称/参数列表。例如:

from en import verb
print verb.tenses()
print verb.infinitive('argue')


['infinitive', 'present participle', 'past plural', '2nd singular present', '2nd singular past', 'past', '3rd singular present', 'past participle', '1st singular present', '1st singular past', '3rd singular past', 'present plural']
    argue
您可以执行
getattr(动词“不定式”)
,它将返回与
verb.infinitive
功能完全相同的引用。然后,您可以循环浏览如下字符串列表:

tense_functions = {
    'infinitive': ('infinitive', {}),
    'present participle': ('present_participle', {}),
    '1st singular present': ('present', {'person': 1}),
    ...
}
for tense in verb.tenses():
    options = tense_functions[tense]
    func = getattr(verb, options[0])
    print(func('argue', **options[1]))
当然,字符串必须是模块中的确切函数名,不管它们是什么


您可能还需要查看
hasattr()
。如果您尝试
getattr()
,但您为该对象提供的属性不存在,您将获得AttributeError。在尝试
getattr之前使用
if hasattr(…
)(…
将让您优雅地处理此类情况。或者,您可以使用try…except块。

是否要对动词进行共轭?如果是,您看过文档了吗?我想要动词的所有形式。我浏览了源代码,找不到一个可以实现此技巧的函数。文档中没有提到类似的函数。请如果我错了,请纠正我。你到底想做什么,但失败了?我必须调用
动词。不定式(),verb.present uu.participle…
。我正在寻找一种速记方法来循环列表字符串。你能提供示例输入和相应的输出吗?你的代码示例不清楚。谢谢!我对python相当陌生。请解释更多,我似乎不太懂。你不能这样做,因为列表必须包含
第二个字符gular_present
并且你不能让函数名以数字开头。(当然,你可以,但不容易,我怀疑你的库会公开它们)是的,我刚刚找到了。所以从注释中删除它。对不起,我的错。请进一步解释代码。我得到以下错误:
名称错误:名称“person”没有定义
漏引号-现在修复。
some_tenses = ['infinitive', 'present_participle', 'past_plural',]
for tense in some_tenses:
    print getattr(verb, tense)('argue')