2015-08-30 36 views
1
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 

Using this使用字符串呼叫功能

我找不到一個給動詞所有時態的方法。只有一種方法可以調用每個函數:使用動詞對象從列表中替換空格。我怎樣才能做到這一點?

輸入:argue。輸出應該是:arguing,argued,argue ..

+1

你想結合動詞嗎?如果是這樣,你看過文檔[這裏](https://www.nodebox.net/code/index.php/Linguistics#verb_conjugation)? – or1426

+0

我想要所有形式的動詞。我瀏覽了源代碼,並沒有辦法實現這個功能。文檔沒有提到這樣的功能。如果我錯了,請糾正我 –

+0

你究竟想做什麼失敗? –

回答

1

您可以爲每個時態名稱創建一個名稱/參數列表。例如:

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])) 
+0

謝謝!我對python相當陌生。請多說明一下,我看起來不能理解太多。 ' –

+1

你不能這樣做,因爲列表必須包含'2nd_singular_present',並且不能有以數字開頭的函數名稱。 (好吧,你可以,但不容易,我懷疑你的圖書館會暴露他們) – viraptor

+0

是的,我只是想通了。所以從評論中刪除它。對不起這是我的錯。請更多地解釋代碼。 –

0

你可以做getattr(verb, 'infinitive'),它會返回一個參考完全相同的功能verb.infinitive。然後,您可以通過類似這樣的字符串列表循環:

some_tenses = ['infinitive', 'present_participle', 'past_plural',] 
for tense in some_tenses: 
    print getattr(verb, tense)('argue') 

當然,字符串必須是模塊中的確切功能名稱,不管他們是。您可能還想看看hasattr()。如果您嘗試使用getattr(),但您提供的屬性對於該對象不存在,您將得到一個AttributeError。在嘗試getattr(...之前使用if hasattr(...可以讓您優雅地處理這種情況。或者,您可以使用try ... except塊。