-1

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

这样的事情可能吗?

谢谢您的帮助!

4

1 回答 1

5

是的。您可以使用getattr

import nltk.corpus
corpus_data = getattr(nltk.corpus, corpus_name)
于 2013-04-12T03:56:58.697 回答