【问题标题】:How to extract a word from a string and assign it to a variable in Python 3.7?如何从字符串中提取单词并将其分配给 Python 3.7 中的变量?
【发布时间】:2020-01-22 11:39:08
【问题描述】:

好的,所以我正在尝试创建这个基本的机器人来回答我使用 Python 3.7 提出的一些问题。

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

现在假设我问:

“字典是什么意思”

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

如何提取单词“字典”以便将其放入变量中?

我还没有尝试过任何具体的解决方案,因为我是 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.

预期的结果应该是:

当有人打字时:

“文字是什么意思”

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

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: python python-3.x pycharm python-3.7


【解决方案1】:

您可以使用 split funktion 将句子拆分为单词列表。

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

然后只提取最后一个单词:

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

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

【讨论】:

  • 刚刚试了一下,效果很好!非常感谢:)
【解决方案2】:

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

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

大概这句话的结尾也可能有一个?,所以也许你想做这样的事情:

lookup.rstrip('?')

【讨论】:

  • 其实我想通了 lmao。我想使用 elif 语句来实现它,有什么想法可以做到吗?
猜你喜欢
  • 2021-12-24
  • 2012-07-17
  • 1970-01-01
  • 2013-05-09
  • 2018-07-24
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多