我想做一個程序,根據用戶輸入診斷計算機問題,並檢查關鍵字。我想要關鍵字在文本文件中。這是迄今爲止的代碼,但它從變量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])
我想做一個程序,根據用戶輸入診斷計算機問題,並檢查關鍵字。我想要關鍵字在文本文件中。這是迄今爲止的代碼,但它從變量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])
您可以用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"
已經回答這裏http://stackoverflow.com/questions/11026959/python-writing-dict to-txt-file-and-reading-dict-from-txt-file –