首页 > 解决方案 > 加速 SpaCy 分词器

问题描述

我正在使用 SpaCy 标记数以万计的文档。平均而言,每个文档大约需要 5 秒。关于如何加快标记器的任何建议?

一些附加信息:

以下是我的代码:

from pathlib import Path, PurePath
from time import time

st = time()
nlp = en_core_web_sm.load(disable = ['ner', 'tagger', 'parser', 'textcat'])
p = Path('input_text/').glob('*.txt')
files = ['input_text/' + x.name for x in p if x.is_file()]

#nlp = spacy.load('en-core-web-sm')

stopwords_file = 'stopwords.txt'

def getStopWords():
    f = open(stopwords_file, 'r')
    stopWordsSet = f.read()
    return stopWordsSet

stopWordsSet = getStopWords()
out_file = 'token_results.txt'
for file in files:
    #print (out_file)
    with open(file, encoding="utf8") as f:
        st_doc = time()
        for line in f:

            doc = nlp(line)

            for token in doc:
                if (not token.text.lower() in stopWordsSet
                    and not token.is_punct and not token.is_space and not token.like_num
                    and len(token.shape_)>1):                    

                    tup = (token.text, '|', token.lemma_)

                    appendFile = open(out_file, 'a', encoding="utf-8")
                    appendFile.write(" " + tup[0])
        print((time() -st_doc), 'seconds elasped for', file)
        appendFile.write('\n')
        appendFile.close()
print((time()-st)/60, 'minutes elasped')

标签: python-3.xspacy

解决方案


  1. 主要问题:打开一次输出文件并保持打开状态,直到脚本结束。反复关闭和​​重新打开并寻找更大的文本文件的末尾将非常缓慢。

  2. 将停用词读入实际的set(). 否则,您将在包含整个文件的长字符串中搜索每个标记,这会意外匹配部分单词并且比检查集合成员资格要慢得多。

  3. 使用 nlp.pipe() 或仅用于标记化 nlp.tokenizer.pipe() 以加快 spacy 部分。对于一堆简短的单句文档,这似乎并没有太大的区别。标记一个大文档比将每一行视为一个单独的文档要快得多,但是您是否要这样做取决于您的数据的结构方式。如果您只是进行标记,则可以根据nlp.max_length需要增加最大文档大小 ( )。

texts = f.readlines()
docs = nlp.tokenizer.pipe(texts)

for doc in docs:
    for token in doc:
        ...

推荐阅读