【问题标题】:Random.choice gives the same answerRandom.choice 给出了相同的答案
【发布时间】:2019-09-19 01:42:26
【问题描述】:

我是新手,想用 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)))

例如,当评论是:“summon_bot 和 summon_bot 是最好的角色”时,这两个短语的答案相同

【问题讨论】:

  • 它只是用随机选择的char1 项目替换phrase 的出现。
  • 您确定它不会引发缩进错误吗?还是缺少冒号的语法错误?

标签: python bots


【解决方案1】:

将您的代码解读为:

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

【讨论】:

    【解决方案2】:

    我认为,这就是你想要做的。

    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)
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 投反对票并标记为不是答案。这应该是一条评论。
      猜你喜欢
      • 2016-03-15
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 2020-10-03
      相关资源
      最近更新 更多