如何在输入python中搜索和打印项目?
我刚开始编写代码,有一个问题。 我正在为一个名为Sasha的聊天机器人编写一个脚本,但是我找不到任何方法来解决一个句子中并非所有单词都匹配的问题。 比如说,我想让它以不同的方式检查日期,而不仅仅是说“日期”。我该怎么做呢? 感谢您的帮助如何在输入python中搜索和打印项目?,python,list,Python,List,我刚开始编写代码,有一个问题。 我正在为一个名为Sasha的聊天机器人编写一个脚本,但是我找不到任何方法来解决一个句子中并非所有单词都匹配的问题。 比如说,我想让它以不同的方式检查日期,而不仅仅是说“日期”。我该怎么做呢? 感谢您的帮助 Database =[ ['hello sasha', 'hey there'], ['what is the date today', 'it is the 13th of October 2017'],
Database =[
['hello sasha', 'hey there'],
['what is the date today', 'it is the 13th of October 2017'],
['name', 'my name is sasha'],
['weather', 'it is always sunny At Essex'],
]
while 1:
variable = input("> ")
for i in range(4):
if Database[i][0] == variable:
print (Database[i][1])
您可以使用dict将输入映射到答案 更新: 添加正则表达式以匹配输入,但我认为您的问题更像NLP问题
import re
Database ={
'hello sasha': 'hey there',
'what is the date today':'it is the 13th of October 2017',
'name': 'my name is sasha',
'weather': 'it is always sunny At Essex',
}
while 1:
variable = input("> ")
pattern= '(?:{})'.format(variable )
for question, answer in Database.iteritems():
if re.search(pattern, question):
print answer
输出:
date
it is the 13th of October 2017
最基本的答案是检查句子中是否有一个单词:
while 1:
variable = input("> ")
for i, word in enumerate(["hello", "date", "name", "weather"]):
if word in input.split(" "): # Gets all words from sentence
print(Database[i][1])
in: 'blah blah blah blah date blah'
out: 'it is the 13th of October 2017'
in: "name"
out: "my name is sasha"
您可以使用“in”检查列表中是否有内容,如:(在伪代码中) 你应该考虑学习词典是什么,这对你有很大帮助。
list = ['the date is blah', 'the time is blah']
chat = input('What would you like to talk about')
if chat in ['date', 'what is the date', 'tell the date']:
print(list[0])
elif chat in ['time', 'tell the time']:
print(list[1])
etc.