我需要找到一种根据用户输入返回句子的方法,即关键字搜索。
我创建了一本词典,可以根据一个单词返回一个句子,但不知道是否可以根据多个单词返回句子:
水伤害返回一句关于将手机放入水中的话我有一个破裂的屏幕不返回任何内容。我知道问题出在我使用的.split.strip函数上。
我的下一个问题是,我似乎无法创建空条目检查,我已经尝试了通常的方法,而input_1为None,或=='',但strip函数删除了空白,所以我猜没有空条目可供选择。
similar_words = {
'water': 'you have let water into your phone',
'wet': 'let your phone dry out then try to restrat the phone',
'crack case': 'you have cracked your screen or case, this will need replacing by a specialist',
'cracked screen': 'you have cracked your screen or case, this will need replacing by a specialist',
'turn on': 'your battery may need replacing',
'crack': 'your phone screen has been cracked, you need to contact the technician centre',
}
def check():
if word.lower() in similar_words:
print(similar_words[word.lower()])
input_1 = input("What seems to be the problem with your phone?: ").strip().split()
for word in input_1:
check()
def close():
print ('Please press enter to close the program')
quit()
close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
close()
else:
print ('Lets us move on then')
如果输入只是"破解屏幕",则对split()
的调用返回两个单词的列表:["cracked", "screen"]
。测试word.lower() in similar_words
有效地将每个单词与查找匹配的字典的所有关键字进行比较。
由于您既没有"破解"也没有"屏幕"作为字典中的键,因此无法找到匹配项。
如果您将输入拆分为一个单词列表,则每个键都需要是一个单词。
但是,如果你把"破解"作为一个键,那么像"我的手机壳被破解了"这样的输入就会被报告,就像它是一个破解的屏幕一样。
你需要一个更聪明的测试,并且可能需要阅读ngrams。将输入拆分为unigram、bigram等,并对照键列表检查每个键。然后你需要弄清楚如何处理输入,比如"我的屏幕被破解了"。
至于NULL检查,如果输入字符串为空,strip().split()
将返回一个空列表([]
)。检查len(input_1) == 0
。
根据你的程序,我认为你只需要显示电话问题的解决方案,但你的程序没有显示它。所以我在程序中做了一些更改,它正在显示它。
similar_words = {
'water': 'you have let water into your phone',
'wet': 'let your phone dry out then try to restart the phone',
'crack case' : 'you have cracked your screen or case, this will need replacing by a specialist',
'cracked screen' : 'you have cracked your screen or case, this will need replacing by a specialist',
'turn on' : 'your battery may need replacing',
'crack' : 'your phone screen has been cracked, you need to contact the technician centre'
}
input_1 = input("What seems to be the problem with your phone?: ").split()
for word in input_1:
if word in similar_words.keys():
print(similar_words[word])
#similar_words[word] gives only the value of the key word
close_1 = input('Have we addressed your problem, please answer yes or no?: ')
if close_1=='yes':
quit()
else:
print ('Lets us move on then')