[英]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()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.