2017-02-02 87 views
0

我想做一個程序,根據用戶輸入診斷計算機問題,並檢查關鍵字。我想要關鍵字在文本文件中。這是迄今爲止的代碼,但它從變量d中讀取關鍵字,而不是從文本文件中讀取。如何檢查文本文件中關鍵字的輸入?

d = {'screen': 'Get a new screen', ...} 
problem = input('What did you do? ').lower() 
for k in d: 
    if k in problem: 
     print(d[k]) 
+0

已經回答這裏http://stackoverflow.com/questions/11026959/python-writing-dict to-txt-file-and-reading-dict-from-txt-file –

回答

0

您可以用JSON格式構造您的文本文件並使用python的json.load(your_file_name)。一個例子是:

# text file: diagnostics.json 
import json 

problems_db = {} # initialize this global variable with default value 
with open('diagnostics.json') as fp: 
    db_content = json.load(fp) 

problem = input('What did you do? ').lower() 
for k in problems_db: 
    if k in problem: 
     print(d[k]) 

實施例:

// diagnostics.json 
{ 
    "slow": "restart your computer", 
    "stuck": "restart your computer", 
    "not loading": "wait a few seconds, then restart your computer" 
} 

用戶交互:

"What did you do?" "my computer is really slow" 
"restart your computer" 
+0

有沒有辦法用.txt文件做到這一點?我的Mac的textedit不能保存爲JSON格式 –

+0

當然,您可以使用這種格式,但將擴展名更改爲.txt – benjaminz

+0

在稍微不相關的註釋中,爲什麼不使用VS代碼或Sublime Text,在所有優秀的文本編輯器中,作爲文本編輯器來維護這個文件? – benjaminz

相關問題