In this post, we will see how to automatically generate multiple-choice questions (MCQs) from any story or article. This is one step towards automatically generating the kind of MCQs you see in middle school and high school.
Input: The input to our program will be an article (an example article is provided in the GitHub repository below), such as the following:
The Greek historian knew what he was talking about. The Nile River fed Egyptian civilization for hundreds of years. The Longest River the Nile is 4,160 miles long — the world’s longest river. It begins near the equator in Africa and flows north to the Mediterranean Sea ..............
Output: The output will be a set of automatically generated MCQs with effective distractors (wrong answer choices):
1) The Nile provided so well for _______ that sometimes they had surpluses, or more goods than they needed.
a ) Angolan
b ) Algerian
c ) Egyptians
d ) Bantu
More options: ['Basotho', 'Beninese', 'Berber', 'Black African', 'Burundian', 'Cameroonian', 'Carthaginian', 'Chadian', 'Chewa', 'Congolese', 'Djiboutian', 'Egyptian', 'Ethiopian', 'Eurafrican', 'Ewe', 'Fulani']
2) As in many ancient societies, much of the knowledge of _______ came about as priests studied the world to find ways to please the gods.
a ) Malawi
b ) East Africa
c ) Somalia
d ) Egypt
More options: ['Togo', 'Zimbabwe', 'Gabon', 'Ghana', 'Lake Tanganyika', 'Ottoman Empire', 'Mozambique', 'Iran', 'Israel', 'Saudi Arabia', 'Lebanon', 'Turkey', 'Iraq', 'Levant', 'Syria', 'Jordan']
3) The _______ provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed.
a ) Nyala
b ) Omdurman
c ) Nile
d ) Port Sudan
More options: ['Khartoum', 'Nubian Desert', 'Darfur', 'Libyan Desert', 'Kordofan', 'Gulu', 'Buganda', 'Entebbe', 'Jinja', 'Lake Edward', 'entebbe', 'gulu', 'kayunga', 'Upper Egypt', 'Suez Canal', 'Aswan High Dam']
Let's start by seeing how you can build your own MCQ generator using the latest natural language processing (NLP) techniques.
(If you would like to try an advanced MCQ generator directly, please visit https://questgen.ai/)
First, install the necessary libraries in a Jupyter notebook. If you run into any error, just adjust the versions and check for other incompatibilities:
!pip install gensim
!pip install git+https://github.com/boudinfl/pke.git
!python -m spacy download en
!pip install bert-extractive-summarizer --upgrade --force-reinstall
!pip install spacy==2.1.3 --upgrade --force-reinstall
!pip install -U nltk
!pip install -U pywsd
import nltk
nltk.download('stopwords')
nltk.download('popular')
BERT Extractive Summarizer
Here we use a simple library, bert-extractive-summarizer, which does this task for us. We load the full text from the egypt.txt file in the GitHub repo and ask the library to give us a summarized text. You can play with parameters such as the ratio and the maximum and minimum length of the sentences to keep in the summary.
from summarizer import Summarizer
f = open("egypt.txt","r")
full_text = f.read()
model = Summarizer()
result = model(full_text, min_length=60, max_length = 500 , ratio = 0.4)
summarized_text = ''.join(result)
print (summarized_text)
We get a summarized portion of the original text as output:
The Nile River fed Egyptian civilization for hundreds of years. It begins near the equator in Africa and flows north to the Mediterranean Sea. A delta is an area near a river’s mouth where the water deposits fine soil called silt.......................
Keyword extraction
We use the Python keyword extractor (PKE) library to extract all the important keywords from the original text, then keep only the keywords that appear in the summarized text. Here I extract only nouns, because they are more suitable for MCQs. I also extract only 20 keywords, but you can play with this parameter (get_n_best).
import pprint
import itertools
import re
import pke
import string
from nltk.corpus import stopwords
def get_nouns_multipartite(text):
out=[]
extractor = pke.unsupervised.MultipartiteRank()
extractor.load_document(input=text)
# not contain punctuation marks or stopwords as candidates.
pos = {'PROPN'}
#pos = {'VERB', 'ADJ', 'NOUN'}
stoplist = list(string.punctuation)
stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']
stoplist += stopwords.words('english')
extractor.candidate_selection(pos=pos, stoplist=stoplist)
# 4. build the Multipartite graph and rank candidates using random walk,
# alpha controls the weight adjustment mechanism, see TopicRank for
# threshold/method parameters.
extractor.candidate_weighting(alpha=1.1,
threshold=0.75,
method='average')
keyphrases = extractor.get_n_best(n=20)
for key in keyphrases:
out.append(key[0])
return out
keywords = get_nouns_multipartite(full_text)
print (keywords)
filtered_keys=[]
for keyword in keywords:
if keyword.lower() in summarized_text.lower():
filtered_keys.append(keyword)
print (filtered_keys)
The output is:
Original text keywords: ['egyptians', 'nile river', 'egypt', 'nile', 'euphrates', 'tigris', 'old kingdom', 'red land', 'crown', 'upper', 'lower egypt', 'narmer', 'longest river', 'africa', 'mediterranean sea', 'hyksos', 'new kingdom', 'black land', 'ethiopia', 'middle kingdom']
Keywords present in summarized text: ['egyptians', 'nile river', 'egypt', 'nile', 'old kingdom', 'red land', 'crown', 'upper', 'lower egypt', 'narmer', 'africa', 'mediterranean sea', 'new kingdom', 'middle kingdom']
Sentence mapping
For each keyword, we extract the corresponding sentences from the summarized text that contain the word.
from nltk.tokenize import sent_tokenize
from flashtext import KeywordProcessor
def tokenize_sentences(text):
sentences = [sent_tokenize(text)]
sentences = [y for x in sentences for y in x]
# Remove any short sentences less than 20 letters.
sentences = [sentence.strip() for sentence in sentences if len(sentence) > 20]
return sentences
def get_sentences_for_keyword(keywords, sentences):
keyword_processor = KeywordProcessor()
keyword_sentences = {}
for word in keywords:
keyword_sentences[word] = []
keyword_processor.add_keyword(word)
for sentence in sentences:
keywords_found = keyword_processor.extract_keywords(sentence)
for key in keywords_found:
keyword_sentences[key].append(sentence)
for key in keyword_sentences.keys():
values = keyword_sentences[key]
values = sorted(values, key=len, reverse=True)
keyword_sentences[key] = values
return keyword_sentences
sentences = tokenize_sentences(summarized_text)
keyword_sentence_mapping = get_sentences_for_keyword(filtered_keys, sentences)
print (keyword_sentence_mapping)
The output is:
{'egyptians': ['The Nile provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed.', 'For example, some ancient Egyptians learned to be scribes, people whose job was to write and keep records.', 'Egyptians believed that if a tomb was robbed, the person buried there could not have a happy afterlife.',
'nile river': ['The Nile River fed Egyptian civilization for hundreds of years.'],
'old kingdom': ['Historians divide ancient Egyptian dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdom.', 'The Old Kingdom started about 2575 B.C., when the Egyptian empire was gaining strength.'], } .....................
MCQ generation
Here we get distractors (wrong answer choices) from WordNet and ConceptNet to generate the final MCQs.
What are distractors (wrong answer choices)?
Suppose “Historians divide ancient Egyptian dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdom”. is our sentence and we want to use the keyword “Egyptian” as the blank to fill; the other, wrong answer choices should then be similar to the word Egyptian, not synonyms of it.
Eg: Historians divide ancient __________ dynasties into the Old Kingdom, the Middle Kingdom, and the New Kingdom
a)Egyptian
b)Ethiopian
c)Angolian
d)Algerian
In the questions above, options b), c) and d) are distractors.
How do we generate these distractors automatically?
We follow two approaches to obtain distractors, one with WordNet and the other with ConceptNet.
The WordNet approach used in our code:
Given a sentence and a keyword as input, we first get the ” sense” of the word.
Let me explain “sense” with an example. If we have the sentence “The bat flew into the jungle and landed on a tree” and the keyword “bat “, we automatically know that we are talking about the winged mammal, not a cricket bat or a baseball bat. Although we humans are good at this, algorithms are not very good at telling one from the other. This is called word sense disambiguation (WSD). In WordNet, the word “bat” may have several senses: one for the cricket bat, one for the flying mammal, and so on. So the get_wordsense function tries to get the correct sense of the word given the sentence it appears in. This is not perfect all the time, so we get some errors when the algorithm settles on the wrong sense. The distractors (wrong answer choices) will then be wrong too.
Once the sense is identified, we call the get_distractors_wordnet function to get the distractors. Suppose we get a word like “cheetah ” and identify its sense; we then go to its hypernym. A hypernym is a higher-level category for a given word. In our example, feline is the hypernym of cheetah.
We then find all the hyponyms (subcategories) of feline, which might be leopard, tiger and lion, all belonging to the feline group. So we can use leopard, tiger and lion as distractors (wrong answer choices) for the given MCQ.
The ConceptNet approach used in our code:
Not all words are available in WordNet, and not all of them have hypernyms. So if WordNet fails, we also look for distractors in ConceptNet. get_distractors_conceptnet is the main function used to get distractors from ConceptNet. ConceptNet has no provision for disambiguating between different senses of a word, as discussed above with the bat example. So we have to go ahead with whichever sense ConceptNet gives us when we query a given word.
Let's see how we use ConceptNet in our use case. We do not install anything, because we use the ConceptNet API directly. Note that the API has an hourly rate limit, so watch out for it.
Given a word such as “California ”, we query ConceptNet and retrieve the “PartOf” relation. In our example, “California” is part of the “United States”.
We now go to the “United States” and see what other things share the “PartOf” relation with it. These will be other states such as “Texas”, “Arizona”, “Seattle” and so on. So for our word “California”, we have fetched the distractors “Texas”, “Arizona” and so on.
import requests
import json
import re
import random
from pywsd.similarity import max_similarity
from pywsd.lesk import adapted_lesk
from pywsd.lesk import simple_lesk
from pywsd.lesk import cosine_lesk
from nltk.corpus import wordnet as wn
# Distractors from Wordnet
def get_distractors_wordnet(syn,word):
distractors=[]
word= word.lower()
orig_word = word
if len(word.split())>0:
word = word.replace(" ","_")
hypernym = syn.hypernyms()
if len(hypernym) == 0:
return distractors
for item in hypernym[0].hyponyms():
name = item.lemmas()[0].name()
#print ("name ",name, " word",orig_word)
if name == orig_word:
continue
name = name.replace("_"," ")
name = " ".join(w.capitalize() for w in name.split())
if name is not None and name not in distractors:
distractors.append(name)
return distractors
def get_wordsense(sent,word):
word= word.lower()
if len(word.split())>0:
word = word.replace(" ","_")
synsets = wn.synsets(word,'n')
if synsets:
wup = max_similarity(sent, word, 'wup', pos='n')
adapted_lesk_output = adapted_lesk(sent, word, pos='n')
lowest_index = min (synsets.index(wup),synsets.index(adapted_lesk_output))
return synsets[lowest_index]
else:
return None
# Distractors from http://conceptnet.io/
def get_distractors_conceptnet(word):
word = word.lower()
original_word= word
if (len(word.split())>0):
word = word.replace(" ","_")
distractor_list = []
url = "http://api.conceptnet.io/query?node=/c/en/%s/n&rel=/r/PartOf&start=/c/en/%s&limit=5"%(word,word)
obj = requests.get(url).json()
for edge in obj['edges']:
link = edge['end']['term']
url2 = "http://api.conceptnet.io/query?node=%s&rel=/r/PartOf&end=%s&limit=10"%(link,link)
obj2 = requests.get(url2).json()
for edge in obj2['edges']:
word2 = edge['start']['label']
if word2 not in distractor_list and original_word.lower() not in word2.lower():
distractor_list.append(word2)
return distractor_list
key_distractor_list = {}
for keyword in keyword_sentence_mapping:
wordsense = get_wordsense(keyword_sentence_mapping[keyword][0],keyword)
if wordsense:
distractors = get_distractors_wordnet(wordsense,keyword)
if len(distractors) ==0:
distractors = get_distractors_conceptnet(keyword)
if len(distractors) != 0:
key_distractor_list[keyword] = distractors
else:
distractors = get_distractors_conceptnet(keyword)
if len(distractors) != 0:
key_distractor_list[keyword] = distractors
index = 1
print ("#############################################################################")
print ("NOTE:::::::: Since the algorithm might have errors along the way, wrong answer choices generated might not be correct for some questions. ")
print ("#############################################################################\n\n")
for each in key_distractor_list:
sentence = keyword_sentence_mapping[each][0]
pattern = re.compile(each, re.IGNORECASE)
output = pattern.sub( " _______ ", sentence)
print ("%s)"%(index),output)
choices = [each.capitalize()] + key_distractor_list[each]
top4choices = choices[:4]
random.shuffle(top4choices)
optionchoices = ['a','b','c','d']
for idx,choice in enumerate(top4choices):
print ("\t",optionchoices[idx],")"," ",choice)
print ("\nMore options: ", choices[4:20],"\n\n")
index = index + 1
Finally, we generate the output as follows:
#############################################################################
NOTE:::::::: Since the algorithm might have errors along the way, wrong answer choices generated might not be correct for some questions.
#############################################################################
1) The Nile provided so well for _______ that sometimes they had surpluses, or more goods than they needed.
a ) Angolan
b ) Algerian
c ) Egyptians
d ) Bantu
More options: ['Basotho', 'Beninese', 'Berber', 'Black African', 'Burundian', 'Cameroonian', 'Carthaginian', 'Chadian', 'Chewa', 'Congolese', 'Djiboutian', 'Egyptian', 'Ethiopian', 'Eurafrican', 'Ewe', 'Fulani']
2) As in many ancient societies, much of the knowledge of _______ came about as priests studied the world to find ways to please the gods.
a ) Malawi
b ) East Africa
c ) Somalia
d ) Egypt
More options: ['Togo', 'Zimbabwe', 'Gabon', 'Ghana', 'Lake Tanganyika', 'Ottoman Empire', 'Mozambique', 'Iran', 'Israel', 'Saudi Arabia', 'Lebanon', 'Turkey', 'Iraq', 'Levant', 'Syria', 'Jordan']
3) The _______ provided so well for Egyptians that sometimes they had surpluses, or more goods than they needed.
a ) Nyala
b ) Omdurman
c ) Nile
d ) Port Sudan
More options: ['Khartoum', 'Nubian Desert', 'Darfur', 'Libyan Desert', 'Kordofan', 'Gulu', 'Buganda', 'Entebbe', 'Jinja', 'Lake Edward', 'entebbe', 'gulu', 'kayunga', 'Upper Egypt', 'Suez Canal', 'Aswan High Dam']
4) It combined the red _______ of Lower Egypt with the white _______ of Upper Egypt.
a ) Capital
b ) Crown
c ) Masthead
d ) Head
More options: []
5) It combined the red Crown of Lower Egypt with the white Crown of _______ Egypt.
a ) Upper Berth
b ) Lower Berth
c ) Upper
More options: []
Note that there may be several errors, either because of the wrong word sense extracted by the WordNet word sense disambiguation (WSD) algorithm, or because the sense identified differs due to its limitations.
What could be improved?
- Just like the “PartOf” relation, ConceptNet has an “IsA” relation that could be explored further to obtain distractors.
- Since we have multiple sentences for each keyword, use all of them for word sense disambiguation (WSD) and choose the sense with the highest count.
- Word vectors (word2vec, GloVe) could be used instead as a way to find distractors for a given word.
- You could apply pronoun resolution (neural coreference resolution) to the full text before passing it to the BERT summarizer. Any sentences with pronouns are then resolved so that they look complete and self-contained when presented as MCQs.

