我是 python 的新手,我正在尝试开发一个电话故障排除程序,我会询问用户他们的设备出了什么问题,如果我的程序检测到“湿”或“水”这个词,它会回复一个结果.另一个例子是“屏幕破裂”。我遇到一个问题,如果我输入“我的屏幕裂了”。我的代码没有检测到它。任何帮助表示赞赏!
我的代码片段:
print(60 * '-')
print('Could you describe what is wrong with your device?')
print(60 * '-')
time.sleep(1)
user_problem = input('')
if user_problem in ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river',):
print('WATERDAMAGE VARAIBLE')
elif user_problem in ('screen', 'cracked', 'shattered', 'smashed',):
print('SCREEN VARIABLE')
请您参考如下方法:
userproblem 是您整个用户的输入。您正在检查它是否属于具有这些关键字的元组。所以,如果输入是 "My phone is wet",这个字符串不属于 ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river',) 因为它不等于这些词中的任何一个。第二个 if 也有同样的问题。
正确的解决方案是询问输入中是否包含这些词中的任何,这是完全相反的。你会有这样的东西:
userproblem_words = userproblem.split(' ')
water_related_words = ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river')
if (any([(word in water_related_words) for word in userproblem_words])):
print('WATERDAMAGE VARIABLE')
break_related_words = ('screen', 'cracked', 'shattered', 'smashed')
elif (any([word in userproblem for word in break_related_words])):
print('SCREEN VARIABLE')
或者,如果您不喜欢这种情况下列表理解的可读性,您可以使用普通的 for:
water_related_words = ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river')
break_related_words = ('screen', 'cracked', 'shattered', 'smashed')
for word in userproblem.split(' '):
if word in water_related_words:
print('WATERDAMAGE VARIABLE')
break
elif word in break_related_words:
print('SCREEN VARIABLE')
break
