Python 3.7 如何从字符串中提取单词并将其分配给变量?

How to extract a word from a string and assign it to a variable in Python 3.7?

好的,所以我正在尝试创建这个基本的机器人来回答我使用 Python 3.7.

提出的一些问题

我需要创建一个系统,当我向它询问某个词的含义时,它会以该词的含义进行回答。为此,我使用了名为 PyDictionary 的模块。

现在假设我问:

"What is the meaning of dictionary"

我想提取单词 "dictionary" 并将其放入一个变量中,然后将该变量放入一些代码中,该代码将找出该单词的含义。

如何提取单词 "dictionary" 以便将其放入变量?

我还没有尝试过任何具体的解决方案,我似乎可以弄清楚其中的逻辑,因为我是 Python 的新手。

#This will be the module I'm importing
from PyDictionary import PyDictionary
dictionary=PyDictionary()

#This line of code will be used to get the meaning:
print (dictionary.meaning("test"))

#The string "text" will be replaced with a variable containing the extracted word.

预期的结果应该是:

当有人输入时:

"What is the meaning of text"

"text" 被提取并放入一个变量中,然后我可以将该变量分配给另一行代码以获取含义。

如果您的单词总是行尾,只需使用 str.split 并取最后一个结果:

phrase = input()
words = phrase.split()
if len(words) > 0:
    lookup = words[-1]
    print (dictionary.meaning(lookup))

大概该短语的末尾也可能有一个 ?,所以您可能想做类似的事情:

lookup.rstrip('?')

您可以使用拆分功能将句子拆分成单词列表。

a="this is an example sentence"
a=a.split()
print(a)

然后只提取最后一个词:

last_word=a[-1] #assigning the first element from behind to a variable

将此变量传递给您的字典模块。