import nltk
req_modules = {'from nltk import punkt': 'punkt',
'from nltk.corpus import stopwords': 'stopwords',
'from nltk import pos_tag': 'averaged_perceptron_tagger',
'from nltk import ne_chunk': 'maxent_ne_chunker'}
for m in req_modules:
try:
print("Trying: '%s'" % m)
exec(m) # try to import the package
print("Success.")
except (LookupError, ImportError):
# if data not found (not already installed), download it
print("Tried: %s. Resource '%s' was not available \
and is being downloaded.\n" % (m, req_modules[m]))
nltk.download(req_modules[m])
exec(m)
I have some code I'm distributing to folks at work, and the lines above are at the top of the file. In order to run the code underneath (which harnesses several subpackages in nltk
), the user needs to have downloaded these subpackages. Is this is safe/reliable way of doing dynamic module import? It has worked for me thus far.