当用户输入短语时,短语中的关键字需要与文本文件中的文本匹配,然后可以将文本文件的行打印回用户。
例如,当用户键入"我的手机屏幕为空白"或"显示屏为空白"时,应该从文本文件向屏幕输出相同的解决方案。
searchfile = open("phone.txt", "r")
question = input (" Welcome to the phone help center, What is the problem?")
if question in ["screen", "display", "blank"]:
for line in searchfile:
if question in line:
print (line)
elif question in ["battery", "charged", "charging", "switched", "off"]:
for line in searchfile:
if question in line:
print (line)
else:
if question in ["signal", "wifi", "connection"]:
for line in searchfile:
if question in line:
print (line)
searchfile.close()
在文本文件中:
屏幕:你的屏幕需要更换电池:你的电池需要充电信号:你没有信号
首先,这两行不符合您的要求:
question = raw_input(" Welcome to the phone help center, What is the problem?")
if question in ["screen", "display", "blank"]:
如果用户键入我的手机屏幕为空,因为整句话不在列表中,则不会执行If的其余部分。相反,你应该测试句子中是否存在列表中的任何成员:
question = raw_input(" Welcome to the phone help center, What is the problem?")
for k in ["screen", "display", "blank"]:
if k in question:
for line in searchfile:
if k in line: # or maybe if 'screen' in line ?
print line
break
break
您可以使用raw_input
这是工作代码:
search_file = open(r"D:phone.txt", "r")
question = raw_input(" Welcome to the phone help center, What is the problem?")
if question in ["screen", "display", "blank"]:
for line in search_file:
if question in line:
print (line)
elif question in ["battery", "charged", "charging", "switched", "off"]:
for line in search_file:
if question in line:
print (line)
else:
if question in ["signal", "wifi", "connection"]:
for line in search_file:
if question in line:
print (line)
search_file.close()