带有模块全局变量的python模块
我制作了一个包含多个函数的python文件,我想将其用作一个模块。假设这个文件名为mymod.py。其中包含以下代码带有模块全局变量的python模块,python,module,global-variables,python-import,Python,Module,Global Variables,Python Import,我制作了一个包含多个函数的python文件,我想将其用作一个模块。假设这个文件名为mymod.py。其中包含以下代码 from nltk.stem.porter import PorterStemmer porter = PorterStemmer() def tokenizer_porter(text):
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\u porter函数中,因为它感觉是多余的。这样做的正确方式是什么?还有,有没有可能避免
from mymod import *
在这种情况下
非常感谢 要在python中访问全局变量,您需要在function中使用
global
关键字指定它
def tokenizer_porter(text):
global porter
return [porter.stem(word) for word in text.split()]
它对我有用。谢谢在这种情况下,是否可以避免mymod导入*?我从mymod import tokenizer\u porter尝试过,但没有成功。在添加了global之后,您尝试过吗?因为它应该起作用