[英]How do I pick a random condition from this loop to print?
這是我的代碼。 它是一個從 subreddit 中查找關鍵字並根據關鍵字發布回復的機器人。
它有 3 個不同的關鍵字可供搜索,每個關鍵字都有一個特定的答案。
但它應該隨機打印出哪個關鍵字:答案。 我該怎么做呢?
有時它會想對“你好”評論說“你好”,有時它會想對“再見”評論說“再見”等等。
每次掃描之間的睡眠時間為 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)
你可以
import random
在列表中移動您的答案
answers =["hi","hello","bye"]
將您的答案更改為
comment.reply(random.choice(answers))
random.choice 將為您選擇一個隨機答案。
如果您有多個關鍵字,這就是您想要的:創建一個答案字典{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
您可以使用要打印的選項創建一個列表,然后隨機選擇一個元素:
import random
l = ["text 1", "text 2", "text 3" ]
print(random.choice(l))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.