Home > OS >  How to get a single random value from an array in python
How to get a single random value from an array in python

Time:07-14

I'm trying to get a single response from an array of responses. I've tried using the random.choice() but i'm getting errors. When i print the response without the random.choice() it prints out the entire array "responses": ["Hello!", "Good to see you again!", "Hi there, "], My code

from chatterbot import ChatBot 
from chatterbot.trainers import ListTrainer 
import chatterbot #Just in case
import os
import random


bot = ChatBot("Test") 
trainer = ListTrainer(bot) #Creates the trainer
data = "C:/Users/Patty/Desktop/chatbotUI/ints/"

for files in os.listdir(data):
conv = open(data   files, 'r').readlines() 
trainer.train(conv) 


while True:
message = input("You: ")

if message.strip() != "Bye":
    response = bot.get_response(message)
answer = random.choice(response)
print("ChatBot: ", answer) 

if message.strip() == "Bye":
    print("ChatBot: Farewell")
    break

Here is my json intents

intents = [

{"tag": "greeting",
"patterns": ["Hi", "How are you", "Is anyone there?", "Whats up"],
"responses": ["Hello!", "Good to see you again!", "Hi there, "],
"context_set": ""
},
]

CodePudding user response:

random.choice returns a value from a sequence (like a list).

It looks like you might be passing a nested data structure with a list further inside.

from random import choice

# Is your data like this?
response = [{"responses": ["Hello!", "Good to see you again!", "Hi there, "]}]
print(choice(response))
# > {'responses': ['Hello!', 'Good to see you again!', 'Hi there, ']}

print(choice(response[0]['responses']))
# > Good to see you again!

CodePudding user response:

If I understand the problem, response is a dictionary, not an array, so you should change

answer = random.choice(response)

to

answer = random.choice(response["responses"])
  • Related