我必须为故障排除系统编写代码,该系统使用用户输入中的关键字来提供文本文件的解决方案。我有一个If语句列表,它指示程序从纺织品中读取特定行,并根据用户输入中存在的特定关键字将它们显示为解决方案。
但是,无论用户输入是什么,程序似乎都会显示文本文件中的前两行(程序似乎卡在第一个if语句中)。
Keywords = ['screen', 'display', 'audio', 'sound',]
Keywords2 = ['cracked', 'broken', 'water', 'frozen', 'unresponsive']
# Collecting the user's problem using user input
problem = input(str("Please enter your problem:")).split()# Assigns the user input to the variable 'progarm' and converts the user input into a string
# Presenting solutions to user if corresponding Keywords are present in the users input 'problem'
if any(i in Keywords or Keywords2 for i in problem): # This while loop checks that any of the keywords (i) in the lists (Keyword or Keywords2) are present in the user's input (problem), which has been splitted into individual words (indicated by spacing - i)
if Keywords[0] or Keywords[1] and Keywords2[0] or Keywords2[1] in problem:
read(0)
read(1)
elif Keywords[0] or Keywords[1] and Keywords2[3] or Keywords2[4] in problem:
read(3)
elif Keywords2[2] in problem:
read(2)
elif Keywords[2] or Keywords[3] and Keywords2[5] or Keywords2[6] in problem:
read(4)
read(0)
当我输入'手机掉入水中'时,它应该检测关键字“水”,即关键字2 [2],并读取文本文件中的第二行。相反,它读取第一个if语句中指向的行。
Please enter your problem:My phone fell into water
Get it repaired at a reliable repair shop
You will need to buy a new screen and a new screen protector
非常感谢任何改进代码并使其有效的建议!
答案 0 :(得分:1)
我认为问题可能在于in
的使用不当。
您可能想要这样做:
any(i in Keywords or i in Keywords2 for i in problem)
而不是
any(i in Keywords or Keywords2 for i in problem)
同样,对于内部if
和elif
语句。
例如:
if (Keywords[0] in problem or Keywords[1] in problem) and (Keywords2[0] in problem or Keywords2[1] in problem):
而不是
if Keywords[0] or Keywords[1] and Keywords2[0] or Keywords2[1] in problem: