具有模块化全局变量的python模块

时间:2016-04-25 03:16:33

标签: python module global-variables python-import

我制作了一个包含多个函数的python文件,我想将它用作模块。假设这个文件名为mymod.py。以下代码在其中。

from nltk.stem.porter import PorterStemmer                      
porter = PorterStemmer()  

def tokenizer_porter(text):                                                                                    
    return [porter.stem(word) for word in text.split()]  

然后我尝试在iPython中导入它并使用tokenizer_porter:

from mymod import * 
tokenizer_porter('this is test')

生成了以下错误

TypeError: unbound method stem() must be called with PorterStemmer instance as first argument (got str instance instead)

我不想把porter放在tokenizer_porter函数中,因为它感觉多余。这样做的正确方法是什么?此外,是否可以避免

from mymod import * 

在这种情况下?

非常感谢!

1 个答案:

答案 0 :(得分:1)

要在python中访问全局变量,您需要使用global关键字

指定它
def tokenizer_porter(text):     
    global porter                                                                           
    return [porter.stem(word) for word in text.split()]  
相关问题