简体   繁体   English

Random.choice 给出了相同的答案

[英]Random.choice gives the same answer

I'm new and wanted to make a reddit bot with random.choice but if I write the same phrase twice in the same comment it gives the same answer我是新手,想用 random.choice 制作一个 reddit 机器人,但如果我在同一个评论中写了两次相同的短语,它会给出相同的答案

phrase = 'summon_bot'

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

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

and when a comment is for example :"summon_bot and summon_bot are the best characters" it gives the same answer for both phrases并且当评论是例如:“summon_bot 和susmon_bot 是最好的角色”时,它对这两个短语给出了相同的答案

I think, that's what you're trying to do.我想,这就是你想要做的。

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)

read your code as:将您的代码阅读为:

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

You need a way to evaluate random.choice(char1) for each occurence.您需要一种方法来评估random.choice(char1) Eg:例如:

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()的文档,它替换它找到的所有事件,而不仅仅是第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM