我是新手,想用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是最好的字符”时,两个短语给出相同的答案
答案 0 :(得分: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)
答案 1 :(得分:2)
将代码读取为:
eleventh_category
您需要一种方法来评估每次发生的class DmozSpiderSpider(scrapy.Spider):
name = 'Dmoz'
start_urls = ['http://dmoz-odp.org/']
eleventh_category = ['A','B','C']
for again in eleventh_category:
save = f'http://dmoz-odp.org/Regional/{again}/'
def parse(self, response):
# collect data on page
items = {
'Navbar': response.css('#main-nav a::text').extract(),
'Category_names': response.css('.top-cat a::text').extract(),
'Subcategories': response.css('.sub-cat a::text').extract(),
# this is eleventh_category
'Eleventh_category': self.save
}
# save and call request to another page
dct = [(self.save, self.alpha_country)]
for page, callback in dct:
yield response.follow(page, callback, meta={'items': items})
def find_items(self, response, names, finder):
items = response.meta['items']
for name, find in zip(names.values(), finder.values()):
items[name] = response.css(find).extract()
yield items
def alpha_country(self, response):
items = response.meta['items']
names = {'name1': 'Countries'}
finder = {'finder1': '.browse-node::text'}
for name, find in zip(names.values(), finder.values()):
items[name] = [i.strip() for i in response.css(find).extract() if i.strip()]
yield items
。
例如:
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
答案 2 :(得分:-1)
查看 replace()的文档,它将替换发现的所有内容,而不仅仅是第一个。