How to assign module name to a variable?
Question: I would like to dynamically let the user chose which body of data he/she would
like to work with. To do this, after the user identifies their "corpus" of
choice, I must import the appropriate corpus. (I am running on Python 2.7.3)

    
    
    corpora_ls = ["gutenberg","inaugural","movie_reviews","state_union"]
    import_validation = False
    
    while not import_validation:
        print "Corpora Options: \"gutenberg\", \"inaugural\", \"movie_reviews\", \"state_union\"."
        import_option = str(raw_input("What corpus would you like to import? "))
    
        if import_option in corpora_ls:
            import_validation = True
    
            if import_option == "gutenberg":
                fname = "gutenberg"
                from nltk.corpus import gutenberg as DATA
            elif import_option == "inaugural":
                fname = "inaugural"
                from nltk.corpus import inaugural as DATA
            elif import_option == "movie_reviews":
                fname = "movie_reviews"
                from nltk.corpus import movie_reviews as DATA
            elif import_option == "state_union":
                fname = "state_union"
                from nltk.corpus import state_union as DATA
        else:
            print "Please enter one of the available corpora as listed.\n"
    

Frankly, this code looks cumbersome to me. I would like to be able to simply
say something to the effect of:

    
    
    if import_option == "gutenberg":
        fname = "gutenberg"
    elif import_option == "inaugural":
        fname = "inaugural"
    
       etc....
    
    from nltk.corpus import import_option as DATA
    

rather than having to do a separate `from nltk.corpus...etc.` for every
`if/elif`

Is something like this possible?

Thanks for the help!


Answer: Yes. You can use `getattr`:

    
    
    import nltk.corpus
    corpus_data = getattr(nltk.corpus, corpus_name)
    

