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

标签 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 * 

在这种情况下?

非常感谢!

最佳答案

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

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

关于具有模块级全局变量的 python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831479/

相关文章:

python - if block 中不支持的操作数类型 TypeError

html - Iframe 未显示在 Drupal 站点中

python - 使用 smtplib 发送邮件在本地部署时有效,但在 swarm 中部署时失败(无法分配请求的地址)

python - 使用 Google Cloud Stackdriver 在 Kubernetes Engine 上记录 Python 代码的重复日志条目

python - 从终端运行 python 程序时添加模块

python - Scrapy跨多个表单请求页面存储项目?元? Python

c++ - 类中的全局和外部

javascript - Chart.JS 全局选项

python - 在 Windows 上为 docker 容器安装 SSL CA 证书

Python:日志记录模块 - 全局