随机选择给出了相同的答案

2024-03-29 08:07:11 发布

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

我是新来的,想做一个reddit机器人随机选择但如果我在同一条评论中写同一个短语两次,它会给出相同的答案

phrase = 'summon_bot'

import random
  char1 = ["character1", "character2", "character3"]

  if phrase in comment.body
     reply = comment.body.replace(phrase,str(random.choice(char1)))

例如,当一条评论是:“召唤机器人和召唤机器人是最好的角色”时,它对这两个短语给出了相同的答案


Tags: 答案importbotcomment评论机器人bodyrandom
3条回答

将代码读作:

phrase = 'summon_bot'

import random
  char1 = ["character1", "character2", "character3"]

  if phrase in comment.body:
     random_choice = random.choice(char1)
     #random_choice is now a stored variable. Fixed, is the same each time you use it
     reply = comment.body.replace(phrase,str(random_choice)) #replaces all occurences of phrase with fixed random_choice

您需要一种方法来计算每个事件的random.choice(char1)。 例如:

reply = comment.body
while phrase in reply:
     random_choice = random.choice(char1)
     reply.replace(phrase, random_choice, 1) #extra argument to only replace first occurence

查看replace()的文档,它将替换找到的所有匹配项,而不仅仅是第一个。你知道吗

我想,这就是你想做的。你知道吗

import random

phrase = "summon_bot"
char1 = ["character1", "character2", "character3"]

reply = comment.body
while phrase in reply:
    reply = reply.replace(phrase, str(random.choice(char1)), 1)

相关问题 更多 >