def get_random_articles_v1(number_of_articles_wanted):
"""Given the wanted number of articles returned, get random wikipedia articles"""
if number_of_articles_wanted == 1:
print(wikipedia.summary(wikipedia.random()))
else:
list_of_articles = wikipedia.random(number_of_articles_wanted)
try:
for a in list_of_articles:
article = a[:]
if ('disambiguation' in wikipedia.page(a).title) or ('it may refer to' in wikipedia.page(a).title):
list_of_articles.remove(a)
list_of_articles.append(wikipedia.random())
print(list_of_articles.index(a)+1," - "+wikipedia.summary(a))
print()
except wikipedia.exceptions.DisambiguationError:
list_of_articles.remove(article)
list_of_articles.append(wikipedia.random(article))
python类random()的实例源码
def wikirandom(self, ctx):
"""Get a random wikipedia page."""
await ctx.trigger_typing()
try:
page_name = wikipedia.random(1)
except:
return await ctx.invoke(self.wikirandom)
try:
wiki = wikipedia.page(page_name)
for attr in ('summary', 'url', 'title'):
if not hasattr(wiki, attr):
return await ctx.invoke(self.wikirandom)
except wikipedia.exceptions.DisambiguationError as e:
return await ctx.invoke(self.wikirandom)
await self.embedwiki(ctx, wiki)
def main():
if len(sys.argv) > 1:
start = sys.argv[1]
else:
start = wikipedia.random()
done = set()
while start != "Philosophy":
done.update([start])
sys.stdout.write(start)
sys.stdout.flush()
with nostderr():
start = next_link(start, done)
if start is None:
print("\nNo more links")
exit()
sys.stdout.write(" ? ")
sys.stdout.flush()
print(start)
print("Length: " + str(len(done) + 1))
def scramble(self, ctx, *, message : str):
"""Scrambles the insides of words"""
def scramble_word(word):
if len(word) < 4:
letters = list(word)
random.shuffle(letters)
return "".join(letters)
else:
letters = list(word[1:-1])
random.shuffle(letters)
return word[0] + "".join(letters) + word[-1]
results = []
for word in message.split(" "):
results.append(scramble_word(word))
await ctx.send(" ".join(results))
def on_message(self, message):
if message.guild is not None and not botdata.guildinfo(message.guild.id).reactions:
return
if (message.author == self.bot.user) or message.content.startswith("?"):
return
random.seed(message.content)
for check in self.reactions:
expression = check["regex"]
if check.get("word"):
expression = "\\b({})\\b".format(expression)
match = re.search(expression, message.clean_content, re.IGNORECASE)
else:
match = re.search(expression, message.clean_content)
if match and (random.random() < check.get("chance", 1.0)):
await message.add_reaction(random.choice(check["reaction"]))
break
def ball(self, ctx, question):
"""Classic Magic 8 Ball"""
responses = (
'It is certain', # yes
'It is decidedly so',
'Without a doubt',
'Yes definitely',
'You may rely on it',
'As I see it, yes',
'Most likely',
'Outlook good',
'Yes',
'Signs point to yes', # uncertain
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
"Don't count on it", # no
'My reply is no',
'My sources say no',
'Outlook not so good',
'Very doubtful'
)
await ctx.trigger_typing()
await asyncio.sleep(3)
await ctx.send(random.choice(responses))
def choose(self, ctx, *choices):
"""Choose from a list."""
await ctx.send(random.choice(choices))
def flip(self, ctx):
"""Flip a coin!"""
await ctx.send(f'I got {random.choice(["Heads", "Tails"])}!')
def number(self, ctx, *, num: int):
"""Get a random fact about a number!"""
req = requests.get('http://numbersapi.com/{}?notfound=floor'.format(num))
await ctx.send(req.text)
def retrieve_random_passage(page, length):
"""Given a wikipedia page and length, retrieves a random passage of text from
the content of the wikipedia page with the given length.
"""
content = page.content
content_length = len(content)
if length > content_length:
length = content_length - 1
start = random.randrange(len(content) - length)
end = start + length
return content[start:end]
def choose(irc, source, msgtarget, args):
choices = args[0].split(",")
if len(choices) > 1 and choices:
choice = random.choice(choices).strip()
if choice:
irc.send("PRIVMSG {} :{}: {}".format(msgtarget, source.nick, choice))
elif not choice:
irc.msg(msgtarget, "{}: I can't give you any choice".format(source.nick))
elif len(choices) == 1:
irc.send("PRIVMSG {} :{}: {}".format(msgtarget, source.nick, args[0]))
def randwiki(irc, source, msgtarget, args):
rand = wikipedia.random(pages=1)
url = wikipedia.page(rand).url
irc.msg(msgtarget, "Random Article: {} - \x1d{}\x1d".format(rand, url))
irc.msg(msgtarget, wikipedia.summary(rand, sentences=2, chars=250, auto_suggest=True))
def ask(self, ctx, *, question : str=""):
"""Answers any question you might have"""
random.seed(question)
for check in self.questions:
if re.search(check["regex"], question):
clip = await self.get_clip(f"dota:{random.choice(check['responses'])}", ctx)
await ctx.send(clip.text)
try:
await self.play_clip(clip, ctx)
except AudioPlayerNotFoundError:
pass # Not needed for this
return
print("didnt match anything for ask")
def create_optional_arguments(parser):
""" Given a parser, create optional arguments."""
parser.add_argument('-R', '--random', help='display n random wikipedia articles (1 <= n <= 10)',
type=int, choices=[i for i in range(1,11)])
parser.add_argument('-r', '--read', help='display the specified summarized wikipedia article', type=str, nargs='+')
parser.add_argument('-rf', '--forever', help='display a random article until the user types stop',
action="store_true")
def get_random_articles_v2():
"""Retrieves random articles until the user types 'stop' """
ans = input('Press enter to continue or stop to stop: ')
while ans != 'stop':
try:
print(wikipedia.summary(wikipedia.random()))
print()
ans = input('Press enter to continue or stop to stop: ')
except wikipedia.exceptions.DisambiguationError:
print(wikipedia.summary(wikipedia.random()))
print()
ans = input('Press enter to continue or stop to stop: ')
def choice(args):
""" Given a namespace, determine what to do based of the parameters given. """
if args.random:
return get_random_articles_v1(args.random)
elif args.read:
return get_wanted_article(args.read)
elif args.forever:
return get_random_articles_v2()
def wikipedia_quiz(number_of_articles, passage_length):
"""Generates a multiple choice quiz to identify the correct wikipedia article that
a random passage is pulled from. The number of articles determines how many choices
you must pick from. The passage length determines the number of characters that the
random passage will be.
"""
print('*** Wikipedia Quiz ***')
logging.info('Quiz is starting')
random_articles = wikipedia.random(number_of_articles)
logging.debug('Random articles: %s', str(random_articles).encode('utf-8'))
correct_article_index = random.randrange(number_of_articles)
page_retrieved = False
while not page_retrieved:
try:
correct_article = random_articles[correct_article_index]
correct_page = wikipedia.page(correct_article)
page_retrieved = True
except wikipedia.exceptions.DisambiguationError:
# Wikipedia provides options to choose from, but if we pick one, the title will be
# much more descriptive (particularly by using parenthesis like so). This usually
# ends up making the guessing too easy. Let's just reroll and put the new random
# article in the place of the old one.
new_random_article = wikipedia.random()
random_articles[correct_article_index] = new_random_article
# Try to obtain a good passage
random_passage = retrieve_random_passage(correct_page, passage_length)
retry = 0
while is_passage_unfair(random_passage, correct_article) and retry < RETRY_AMOUNT_MAX:
logging.info('Passage is unfair, generating a new one...')
random_passage = retrieve_random_passage(correct_page, passage_length)
retry += 1
if retry >= RETRY_AMOUNT_MAX:
print('Too many retries for the passage...')
logging.error('Too many retries for the passage...')
return False
# Print info to user
print('...%s...' % random_passage)
encode_utf8 = sys.version_info.major == 2 # Hack support for Python 2
for index, random_article in enumerate(random_articles):
if encode_utf8:
random_article = random_article.encode('utf-8')
print('%d: %s' % (index, random_article))
# Handle answer
answer = request_answer(number_of_articles)
if answer == str(correct_article_index):
print('Correct!')
logging.info('Correct, answer was %d', correct_article_index)
else:
print('Incorrect, answer was: %d' % correct_article_index)
logging.info('Incorrect, answer was: %d', correct_article_index)
logging.info('Quiz is ending')
return True