我想用Flask在Heroku上运行一个webapp。webapp是在Python中使用NLTK(自然语言工具包库)编程的。
其中一个文件具有以下头:
import nltk, json, operator
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
调用包含stopwords代码的网页时,将产生以下错误:
LookupError:
**********************************************************************
Resource 'corpora/stopwords' not found. Please use the NLTK
Downloader to obtain the resource: >>> nltk.download()
Searched in:
- '/app/nltk_data'
- '/usr/share/nltk_data'
- '/usr/local/share/nltk_data'
- '/usr/lib/nltk_data'
- '/usr/local/lib/nltk_data'
**********************************************************************
使用的确切代码:
#remove punctuation
toker = RegexpTokenizer(r'((?<=[^\w\s])\w(?=[^\w\s])|(\W))+', gaps=True)
data = toker.tokenize(data)
#remove stop words and digits
stopword = stopwords.words('english')
data = [w for w in data if w not in stopword and not w.isdigit()]
当stopword = stopwords.words('english')
被注释掉时,Heroku上的webapp不会产生查找错误。
代码在本地计算机上运行时没有故障。我已使用
pip install requirements.txt
当我在计算机上测试代码时,Heroku提供的虚拟环境正在运行。
我也尝试过两个不同来源提供的NLTK,但是LookupError
仍然存在。我使用的两个来源是:
http://pypi.python.org/packages/source/n/nltk/nltk-2.0.1rc4.zip
https://github.com/nltk/nltk.git
问题是语料库(本例中为“stopwords”)没有上传到Heroku。您的代码在本地计算机上工作,因为它已经有了NLTK语料库。请按照以下步骤解决问题。
nltk.data.path.append('path_to_nltk_data')
添加到实际使用nltk的Python文件。希望能解决问题。为我工作!
更新
As Kenneth Reitz pointed out,一个更简单的解决方案已经添加到heroku python构建包中。将
nltk.txt
文件添加到根目录并在其中列出您的语料库。有关详细信息,请参见https://devcenter.heroku.com/articles/python-nltk。原始答案
这里有一个更干净的解决方案,允许您直接在Heroku上安装NLTK数据,而无需将其添加到git repo中。
我使用类似的步骤在Heroku上安装Textblob,Heroku使用NLTK作为依赖项。在步骤3和步骤4中,我对原来的代码做了一些小的调整,这些调整只适用于NLTK安装。
默认的heroku构建包包含一个^{} step ,它在所有默认构建步骤完成后运行:
如您所见,它在您的项目目录中查找您自己的
post_compile
文件(位于bin
目录中),如果它存在,它将运行它。您可以使用这个钩子来安装nltk数据。在本地项目的根目录中创建
bin
目录。将您自己的
post_compile
文件添加到bin
目录。将您自己的
install_nltk_data
文件添加到bin
目录。将
nltk
添加到requirements.txt
文件中(如果使用的是Textblob,则添加textblob
)。在heroku应用程序上设置NLTK_数据环境变量。
post_compile
步骤触发器,然后是nltk下载。希望你能帮上忙!享受吧!
相关问题 更多 >
编程相关推荐