当用户输入短语时,短语中的关键词需要与文本文件中的文本匹配,然后文本文件中的行可以打印回给用户。
e.g。当用户输入“我的手机屏幕为空白”或“显示屏为空白”时,应该有相同的解决方案从文本文件输出到屏幕。
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()
在文本文件中:
屏幕:您的屏幕需要更换电池:您的电池需要充电信号:您没有信号
答案 0 :(得分:0)
您可以使用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()
答案 1 :(得分:0)
首先,这2行不符合您的要求:
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