在带有nltk的Python3中,如果某个单词是动词、名词,如何返回true。

2024-05-16 06:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如果输入中的第一个单词是动词,我需要函数返回true。 我试过了,但没用(aka没有返回任何东西,尽管它是一个动词),有人能给我举个例子说明我做错了什么。还有一个例子说明正确的方法是什么,谢谢!在

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

Tags: 方法函数truedef动词result单词what
3条回答

试试这个:

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

我不知道这个代码列表是否是最新的,但是this是下面代码中动词代码的源代码。在

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()

样本输出:

^{pr2}$

看看代码中的注释,如果您有任何问题,请告诉我。在

使用

nltk.word_tokenize(word)

(当然,您需要导入nltk

^{pr2}$

nltk.pos_tag()

返回“VB”或“VBP”等

相关问题 更多 >