使用条件来查找字符串中的单词

时间:2016-12-10 20:52:06

标签: python

我目前正在尝试制作一个程序,以帮助用户修复手机,具体取决于他们输入的输入

我有一个问题,如果有人回答他们的屏幕不能正常工作,它会将解决方案打印成两个答案。

import string
punct = set(string.punctuation)

sentence = input('Please enter what is wrong with your phone ').lower()

sentence2 = ''.join(x for x in sentence if x not in punct)

if 'smashed' and 'screen' in sentence2:
    print ('Send your phone off for repairs')

if 'screen' and 'not' and 'working' in sentence2:
    print ('Charge your phone')

这是我的错误:

1 个答案:

答案 0 :(得分:0)

要检查是否在句子中找到了一组关键字,您需要使用if word1 in sentence and word2 in sentenceif all(...)

diagnosis = {
    'Send your phone off for repairs': ['smashed', 'screen'],
    'Charge your phone': ['screen', 'not', 'working']
}
for solution, words in diagnosis.items():
    if all(word in sentence for word in words):
        print(solution)