wikipedia_quiz.py 文件源码

python
阅读 28 收藏 0 点赞 0 评论 0

项目:WikipediaQuiz 作者: NicholasMoser 项目源码 文件源码
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
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号