0

I am trying to make a programme which diagnoses a computer problem based on user input and checks for keywords. I want the keywords to be in a text file. This is the code I have so far, but it reads the keywords from the variable d, not from a text file.

d = {'screen': 'Get a new screen', ...}
problem = input('What did you do? ').lower()
for k in d:
    if k in problem:
        print(d[k])
martineau
  • 119,623
  • 25
  • 170
  • 301
  • already answered here http://stackoverflow.com/questions/11026959/python-writing-dict-to-txt-file-and-reading-dict-from-txt-file – Daniel Puiu Feb 02 '17 at 21:45

1 Answers1

0

You can structure your text file in JSON format and use python's json.load(your_file_name). An example would be:

# 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])

Example:

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

User interaction:

"What did you do?" "my computer is really slow"
"restart your computer"
benjaminz
  • 3,118
  • 3
  • 35
  • 47
  • is there any way to do this with a .txt file? my mac's textedit does not save in JSON format – mr.python Feb 02 '17 at 20:44
  • Of course, you can just use this format but change the extension to .txt – benjaminz Feb 02 '17 at 20:45
  • On a slightly irrelevant note, why not using VS Code or Sublime Text, among all great text editors out there, as text editor to maintain this file? – benjaminz Feb 02 '17 at 20:47
  • when i change the extensions of diagnostics.json to .txt i get a long error code??? I am a python noob who need guidance – mr.python Feb 02 '17 at 20:54
  • @mr.python just tested myself and it seems to work. Did it work when extension is `.json`? – benjaminz Feb 03 '17 at 16:47
  • why would i still import json if I'm using a .txt file? – mr.python Feb 04 '17 at 20:25
  • where it says fp, do i put the name and file extension of my text file? sorry I'm so noob – mr.python Feb 04 '17 at 20:44
  • @mr.python no worries, using `import json` is because with JSON, you can access your data with key-value pairs very easily; for your second question, fp is just a variable here, just make sure the `fp` in the `with` statement is consistent with the `json.load(fp)` expression. – benjaminz Feb 06 '17 at 16:07