2016-06-08 38 views
1

当用户输入一个词组时,短语中的关键词需要与文本文件中的文本匹配,然后将该行输出文本文件可以打印回给用户。在文本文件中搜索与用户输入的文本匹配的文本行Python

例如当用户输入“我的手机屏幕为空白”或“显示屏幕为空白”时,应从文本文件中输出相同的解决方案。

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

可以分享phone.txt文件吗?如果不是保密的话。 –

回答

0

首先这些二里内斯不起作用按您的要求:

question = raw_input(" Welcome to the phone help center, What is the problem?") 
if question in ["screen", "display", "blank"]: 

如果用户键入我的手机屏幕是空白,作为完整的句子是不是列表的成员的,如果不会被执行剩余。您应该测试一下列表中是否存在任何列表成员:

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 
+0

谢谢你的帮助。这个程序现在工作! :) – Spinellie

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() 
相关问题