Python 如何检查文本文件中的关键字输入?
我正在尝试制作一个程序,根据用户输入诊断计算机问题,并检查关键字。我希望关键字在文本文件中。这是我到目前为止的代码,但它从变量Python 如何检查文本文件中的关键字输入?,python,python-3.x,parsing,keyword,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]) 您可以用JSON格式构造文本文件,并使用python的
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(您的文件名)
。例如:
# 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"
有没有办法用.txt文件来实现这一点?我的mac的textedit不保存为JSON格式当然,你可以使用这种格式,但将扩展名改为.txtOn一个稍微不相关的注释,为什么不使用VS代码或升华文本,在所有优秀的文本编辑器中,作为文本编辑器来维护这个文件?当我将diagnostics.json的扩展名更改为.txt时,我得到一个很长的错误代码???我是一个需要帮助的巨蟒guidance@mr.python我刚测试过自己,它似乎起作用了。当扩展名为
.json
时,它能工作吗?这里已经回答了