【问题标题】:How to check an input for keywords from a text file?如何检查文本文件中关键字的输入?
【发布时间】:2017-02-02 20:30:30
【问题描述】:

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

【问题讨论】:

标签: python python-3.x parsing keyword


【解决方案1】:

您可以以 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"

【讨论】:

  • 有什么办法可以用 .txt 文件做到这一点?我的 mac 的 textedit 不以 JSON 格式保存
  • 当然,你可以只使用这种格式,但将扩展名改为.txt
  • 有点无关紧要,为什么不使用 VS Code 或 Sublime Text,在所有优秀的文本编辑器中,作为文本编辑器来维护这个文件?
  • 当我将 diagnostics.json 的扩展名更改为 .txt 时,我得到一个很长的错误代码???我是一个需要指导的python菜鸟
  • @mr.python 刚刚测试了自己,它似乎有效。当扩展名是.json时它是否有效?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 2020-04-25
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多