【发布时间】:2018-02-15 22:00:52
【问题描述】:
我正在 Python 3 中进行自然语言处理 (NLP),更具体地说,是在哈利波特系列书籍中进行命名实体识别 (NER)。我正在使用 StanfordNER,效果很好,但需要花费大量时间......
我在网上做了一些研究,为什么它会这么慢,但我似乎找不到任何真正适合我的代码的东西,老实说,我认为问题更多在于我编写代码的(坏)方式.
这就是我现在写的:
import string
from nltk.tokenize import sent_tokenize, word_tokenize
import nltk.tag.stanford as st
tagger = st.StanfordNERTagger('_path_/stanford-ner-2017-06-09/classifiers/english.all.3class.distsim.crf.ser.gz', '_path_/stanford-ner-2017-06-09/stanford-ner.jar')
#this is just to read the file
hp = open("books/hp1.txt", 'r', encoding='utf8')
lhp = hp.readlines()
#a small function I wrote to divide the book in sentences
def get_sentences(lbook):
sentences = []
for k in lbook:
j = sent_tokenize(k)
for i in j:
if bool(i):
sentences.append(i)
return sentences
#a function to divide a sentence into words
def get_words(sentence):
words = word_tokenize(sentence)
return words
sentences = get_sentences(lhp)
#and now the code I wrote to get all the words labeled as PERSON by the StanfordNER tagger
characters = []
for i in sentence:
characters = [tag[0] for tag in tagger.tag(get_words(sentences[i])) if tag[1]=="PERSON"]
print(characters)
正如我所解释的,现在的问题是代码需要大量时间......所以我想知道,这是正常的还是 我可以通过以更好的方式重写代码来节省时间吗? 如果是这样,你能帮帮我吗?
【问题讨论】:
-
需要多少时间?
标签: python python-3.x nlp stanford-nlp named-entity-recognition