作为输出的随机字符串

2024-09-25 02:37:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着写一段代码,从列表中随机抽取一个同义词。 相反,我得到的是一个随机字符串,似乎与我的任何代码都没有关系

主要模块代码如下:

from output import *
import definitions
from responses import *

…

def respond(wordList):
    output = ""
    for word in wordList:
        output = (output + " " + (random.choice(word)))
    return output

def edison():
    mood = ask("Hi, " + username + "! How are you today? ")
    if mood.lower() in definitions.positive:
        print(respond(['i_am', 'happy', 'to' 'hear', 'that']) + "!")
    elif mood.lower() in definitions.negative:
        print(respond(['i_am', 'sorry_unhappy', 'to' 'hear', 'that']) + "!")

…

edison()

以下是responses.py的代码:

i_am = ["I am", "I'm"]
happy = ["cheerful", "delighted", "glad", "joyful", "joyous", "overjoyed", "pleased", "thrilled", "gleeful", "happy"]
sorry_unhappy = ["sorry"]
to = ["to"]
hear = ["listen to", "hear"]
that = ["that"]

以下是我的输出示例:

Hi, Test User! How are you today? bad
 m _ h h!

Tags: to代码infromimportoutputthatresponses
2条回答

问题很可能是random.choice(word)。word是wordList的一个元素,从字符串中随机选择一个字母。试试random.choice(wordList)

如果要将单词列表连接为输出,因为它看起来已经像一个句子了,可以这样做:

output = " ".join(wordList)

您使用的不是来自“responses.py”的内置响应,而是固定的str响应

edison替换为:

def edison():
    mood = ask("Hi, " + username + "! How are you today? ")
    if mood.lower() in definitions.positive:
        print(respond([i_am, happy, to, hear, that]) + "!")
    elif mood.lower() in definitions.negative:
       print(respond([i_am, sorry_unhappy, to, hear, that]) + "!")

相关问题 更多 >