简体   繁体   English

如何从这个循环中选择一个随机条件来打印?

[英]How do I pick a random condition from this loop to print?

Here is my code.这是我的代码。 It is a bot that finds keywords from a subreddit and posts a reply based on the keyword.它是一个从 subreddit 中查找关键字并根据关键字发布回复的机器人。
It has 3 different keywords to search for, and a specific answer to each keyword.它有 3 个不同的关键字可供搜索,每个关键字都有一个特定的答案。
But it should randomize which keyword:answer to print out.但它应该随机打印出哪个关键字:答案。 How do I do this?我该怎么做呢?
Sometimes it will want to say "Hello" to 'hello' comments, other times 'Goodbye' to 'goodbye' comments and so on.有时它会想对“你好”评论说“你好”,有时它会想对“再见”评论说“再见”等等。
It has a sleeptime of 10 minutes between each scan.每次扫描之间的睡眠时间为 10 分钟。

import random
import time

hello_comment = "Hello"
goodbye_comment = "Goodbye"
it_is_true = "It is true"

for submission in subreddit.hot(limit=10):
    print(submission.title)

    for comment in submission.comments:
        if hasattr(comment, "body"):
            comment_lower = comment.body.lower()
            if " hello " in comment_lower:
                print(comment.body)
                comment.reply(penge_comment)
            elif " goodbye" in comment_lower:
                print(comment.body)
                comment.reply(koster_comment)
            elif " is it true? " in comment_lower:
                print(comment.body)
                comment.reply(it_is_true)
            
            time.sleep(600)

you can你可以

import random

move your answers in a list在列表中移动您的答案

answers =["hi","hello","bye"]

change your answer to将您的答案更改为

comment.reply(random.choice(answers))

random.choice will pick a random answer for you. random.choice 将为您选择一个随机答案。

This is what you want if you have multiple keywords: Create a answers dict {keyword: list[answer,]}如果您有多个关键字,这就是您想要的:创建一个答案字典{keyword: list[answer,]}

answers = {"keyword1":["a","b"],"keyword2":["c","d"]}

for keyword in answers:
   if keyword in comment_lower:
      comment.reply(random.choice(answers[keyword]))
      break

You can create a list with the options you want to print and choose one element randomly:您可以使用要打印的选项创建一个列表,然后随机选择一个元素:

import random

l = ["text 1", "text 2", "text 3" ]

print(random.choice(l))

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

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