Я хочу рандомизировать ответы в Python для пользовательского навыка Alexa, проект вопрос-ответ - PullRequest
0 голосов
/ 26 мая 2019

Я создаю навык для Алексы, где она ответит на вопрос «Кто прав, я или ...». Я следовал здесь учебнику https://medium.com/crowdbotics/how-to-build-a-custom-amazon-alexa-skill-step-by-step-my-favorite-chess-player-dcc0edae53fb, но мне нужно рандомизировать ответы Алекса

Player_LIST = ["me or my wife", "me or my husband"]
Player_BIOGRAPHY = {"me or my wife":"She is.",

"me or my husband":"He is."}
#------------------------------Part3--------------------------------
# Here we define the Request handler functions

def on_start():
    print("Session Started.")

def on_launch(event):
    onlunch_MSG = "Hi, you could say, for example: who is right me or my husband?"
    reprompt_MSG = "you can say, who is right, me or my wife?"
    card_TEXT = "Who is right, me or... ?."
    card_TITLE = "Choose your question."
    return output_json_builder_with_reprompt_and_card(onlunch_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def on_end():
    print("Session Ended.")
#---------------------------Part3.1.1-------------------------------
# Here we define the intent handler functions

def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(Player_BIOGRAPHY[name.lower()], card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

Когда я говорю «Алекса, кто прав, я или моя жена?», Она всегда говорит: «Она есть». Я хочу, чтобы она каждый раз давала мне разные ответы, такие как:или он или она или слушай свою жену!или, конечно, вы или любой другой ответ.Я пытался сделать это:

Player_BIOGRAPHY = {"me or my wife":"She is.",
"me or my wife":"you.",
"me or my wife":"Of course your wife",

"me or my husband":"He is.",
"me or my husband":"You are right.",
"me or my husband":"He is not right."}

, но Алекса всегда выбирает только последний ответ «Конечно, твоя жена».Как я могу рандомизировать многие из этих ответов?Я не знаю, как кодировать, но если я зашел так далеко, я смогу сделать это с вашей помощью, пожалуйста.Я могу опубликовать весь код, он вдвое больше, чем здесь.

1 Ответ

0 голосов
/ 26 мая 2019

Player_BIOGRAPHY - это dict, что означает, что каждый ключ имеет только одно значение. Если вы инициализируете его как

Player_BIOGRAPHY = {"me or my wife":"She is.",
"me or my wife":"you.",
"me or my wife":"Of course your wife",

"me or my husband":"He is.",
"me or my husband":"You are right.",
"me or my husband":"He is not right."}

Фактический вывод на печать:

{'me or my wife': 'Of course your wife', 'me or my husband': 'He is not right.'}

Что вам нужно сделать, это составить список возможных ответов для каждого ключа, а затем использовать что-то вроде random.choice, чтобы выбрать из списка. Вот так

Player_BIOGRAPHY = {"me or my wife": ["She is.","you.","Of course your wife"],

"me or my husband": ["He is.","You are right.","He is not right."]}

А для случайного выбора (нужно import random)

random.choice(Player_BIOGRAPHY[name.lower()])
# This will select a random item from the list mapped to name.lower()

Итак, ваш полный код будет выглядеть следующим образом:

import random # this can be at the top of the file too
def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(random.choice(Player_BIOGRAPHY[name.lower()]), card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)
...