如何为变量分配模块名称?

时间:2013-04-12 03:53:32

标签: python python-2.7 import module

我想动态地让用户选择他/她想要使用的数据体。为此,在用户识别出他们选择的“语料库”之后,我必须导入适当的语料库。 (我在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"

坦率地说,这段代码对我来说很麻烦。我希望能够简单地说出以下结果:

if import_option == "gutenberg":
    fname = "gutenberg"
elif import_option == "inaugural":
    fname = "inaugural"

   etc....

from nltk.corpus import import_option as DATA

而不是必须为每个from nltk.corpus...etc.

单独if/elif

这样的事情可能吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

是。您可以使用getattr

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