2017-07-17 86 views
0

如何返回true如果輸入中的第一個單詞是動詞,我需要我的函數返回true。 我試過這個,但它不起作用(即使它是一個動詞也沒有返回任何東西),有人可以告訴我一個我做錯了什麼的例子。還有一個正確的做法是,謝謝你!在Python3與nltk如果某個單詞是動詞,如果某個單詞是動詞,名詞.etc

def All(): 
    what_person_said = input() 
    what_person_said_wt = nltk.word_tokenize(what_person_said) 
    result = nltk.pos_tag(what_person_said_wt[0]) 
    if result == 'VB': 
     print ("First word is a verb") 
     return True 
+0

你是什麼意思的「沒有工作」? –

+0

應該返回true但沒有 –

+0

嘗試打印結果,它會幫助調試 –

回答

0

試試這個:

def All(): 
    what_person_said = input() 
    what_person_said_wt = nltk.word_tokenize(what_person_said) 

    result = str(nltk.pos_tag(what_person_said_wt[0])) 
    print(result) 
    if len(result.split(',')[1].split("VB"))>0: 
     print ("First word is a verb") 
     return True 
+0

好吧,我會試試看,謝謝! –

+0

剛編輯它。 –

0

我不知道這段代碼列表是最新的,但this是在下面的代碼爲VERB_CODES源。

import nltk 

# A verb could be categorized to any of the following codes 
VERB_CODES = { 
    'VB', # Verb, base form 
    'VBD', # Verb, past tense 
    'VBG', # Verb, gerund or present participle 
    'VBN', # Verb, past participle 
    'VBP', # Verb, non-3rd person singular present 
    'VBZ', # Verb, 3rd person singular present 
} 

def All(): 
    print ("Please provide a sentence:") 
    user_provided_input = input() 

    # TEST SENTENCE (instead of requiring user input) 
    # user_provided_input = "Running is fun." 

    print ("The user provided: {}".format(user_provided_input)) 

    # tokenize the sentence 
    user_provided_input_token = nltk.word_tokenize(user_provided_input) 
    print ("The user input token: {}".format(user_provided_input_token)) 

    # [tag][2] the tokens 
    result = nltk.pos_tag(user_provided_input_token) 
    print ("Result: {}".format(result)) 

    # only look at the first word 
    first_word_result = result[0] 
    print ("First word result: {}".format(first_word_result)) 

    # get the first word's corresponding code (or tag?) 
    first_word_code = first_word_result[1] 
    print ("First word code: {}".format(first_word_code)) 

    # check to see if the first word's code is contained in VERB_CODES 
    if first_word_code in VERB_CODES: 
     print ("First word is a verb") 
     return True 
    else: 
     print("First word is not a verb") 
     return False 

def main(): 
    All() 

if __name__ == "__main__": 
    main() 

輸出示例:

Please provide a sentence: 
Runnning is fun. 
The user provided: Runnning is fun. 
The user input token: ['Runnning', 'is', 'fun', '.'] 
Result: [('Runnning', 'VBG'), ('is', 'VBZ'), ('fun', 'NN'), ('.', '.')] 
First word result: ('Runnning', 'VBG') 
First word code: VBG 
First word is a verb 

看看在代碼中的註釋,讓我知道,如果你有任何問題。

+0

非常感謝,這真是太棒了,我希望它能起作用,我會去測試它! –

相關問題