【发布时间】:2013-03-02 01:05:54
【问题描述】:
我正在使用 NLTK 和 Flask 构建一个 Web 应用程序。这只是一个简单的 RESTful 应用程序,我将它部署在 heroku 上,一切顺利。但是,当服务器开始收到更多请求时,我达到了 heroku 的内存限制,即 1.5GB。所以,我猜这是因为每次请求到来时我都在加载nltk.RegexpParser。
这是非常简单的代码。
@app.route('/get_keywords', methods=['POST'])
def get_keywords():
data_json = json.loads(request.data)
text = urllib.unquote(data_json["sentence"])
keywords = KeywordExtraction().extract(text)
return ','.join(keywords)
这是关键字提取位。
import re
import nltk
nltk.data.path.append('./nltk_data/')
from nltk.corpus import stopwords
class KeywordExtraction:
def extract(self, text):
sentences = nltk.sent_tokenize(text)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]
grammar = "NP: {}"
cp = nltk.RegexpParser(grammar)
tree = cp.parse(sentences[0])
keywords = [subtree.leaves()[0][0] for subtree in tree.subtrees(filter=lambda t: t.node == 'NP')]
keywords_without_stopwords = [w for w in keywords if not w in stopwords.words('english')]
return list(set(keywords_without_stopwords + tags))
我不确定这是我的代码、Flask 还是 NLTK 的问题。我对 Python 很陌生。任何建议将不胜感激。
我通过 blitz.io 对此进行了测试,仅在 250 个请求之后,服务器就炸毁并开始抛出 R15。
【问题讨论】:
-
您可以将
cp设为静态类变量(请参阅stackoverflow.com/questions/68645/…)。我怀疑这会解决你的问题。你也可以用 stopwords.words('english') 试试这个,这样你就不会创建很多该列表的实例。那么你应该只创建一个 KeywordExtractor 并一直使用它,而不是为每个请求创建一个。
标签: python performance memory-leaks nltk