2016-06-08 67 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() 
相關問題