如何检查文本文件中关键字的输入?

时间:2017-02-02 20:30:30

标签: python python-3.x parsing keyword

我正在尝试制作一个程序,根据用户输入诊断计算机问题并检查关键字。我希望关键字在文本文件中。这是我到目前为止的代码,但它从变量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])

1 个答案:

答案 0 :(得分:0)

您可以使用JSON格式构建文本文件并使用python' s 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"