psychoSherlock
psychoSherlock

Reputation: 122

How to get random replies for a input from json in python

I have a json file containing some rules . This is an example:

[
  {
    "triggers": ["hello", "hey", "hi"],
    "replies": [
      {
        "reply": "Hey there"
      },
      {
        "reply": "Hola"
      },
      {
        "reply": "Hello World"
      }
    ]
  },
  {
    "triggers": ["who are you", "your name"],
    "replies": [
      {
        "reply": "some name"
      },
      {
        "reply": "lorem ipsum"
      }
    ]
  }
]

What I am trying to achive is if a user queries a text, let's say "hello" I want the script to search through the json file and see if the query exists in any trigger array. If it exists, then I want the script to pick a random reply from the replies array.

I can:

I can't:

I've tried everything. Please help me if you could. Thank you for helping.

Upvotes: 2

Views: 411

Answers (2)

Shreyansh
Shreyansh

Reputation: 476

As you mentioned that you can modify the JSON and your concern is time too,

Consider this JSON,

{
    "query_reply_mapping": {
        "hello": "1",
        "hey": "1",
        "hi": "1",
        "who are you": "2"
    },
    "replies": {
        "1": ["Hey there", "Hola", "Hello World"],
        "2": ["some name", "lorem"]
    }

}

In the above JSON, query_reply_mapping is a mapping between the query and the possible reply array. The "1" and "2" here are the keys pointing to the possible replies for this query in the replies dictionary.

import random
json_data = {}
query="hello"
random.choice(json_data["replies"][json_data["query_reply_mapping"][query]])

This solution will be without loops and much faster than any other. Also, you can create a small script to modify your existing JSON to this that will be a one-time thing.

Upvotes: 1

crayxt
crayxt

Reputation: 2405

We can use random.choice(...) to pick a random element from a sequence. Notice that it will raise an error if sequence is empty. Assuming s is your list of dictionaries:

import random
def reply(greet):
    for e in s:
        if greet in e["triggers"]:
            return random.choice(e["replies"])["reply"]
    return ""

>>> reply("hey")
'Hey there'
>>> reply("hey")
'Hey there'
>>> reply("hey")
'Hello World'
>>> reply("hey")
'Hello World'
>>> reply("hey")
'Hola'
>>> reply("who are you")
'lorem ipsum'
>>> reply("who are you")
'some name'
>>> reply("not exist")
''

Upvotes: 6

Related Questions