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

python module with module-wise global variable

我制作了一个 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 * 

在这种情况下?

非常感谢!

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

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