Я пытаюсь идентифицировать все имена в романе (в виде текстового файла), используя NLTK. В меньших масштабах POS-теги работают отлично. Однако, когда я передаю большой объем текста, под которым я подразумеваю три или четыре абзаца, система терпит неудачу. Как я могу это исправить?
Я прочитал файл, разделил его на строки, предложения, а затем слова. То, что я получаю, это список списков, где каждый внутренний список содержит слова предложения. Затем я использую NLTK, чтобы пометить каждое предложение.
def process_file(_file, tagger, stemmer, stopwords, filename, printinfo):
sentences = []
_nnp = set()
words = dict()
for line in _file:
for sentence in nltk.tokenize.sent_tokenize(line):
sentences.append(nltk.tokenize.word_tokenize(sentence))
sent_count = 0
for sentence in sentences:
sent_count+=1
tags = tagger.tag(sentence)
for tag in tags:
if tag[1] == "NNP" or tag[1] == "NNPS":
_nnp.add(tag[0])
else:
if tag[0] not in stopwords:
stemmed_word = stemmer.stem(tag[0])
if stemmed_word not in words.keys():
words[stemmed_word] = 1
else:
words[stemmed_word] += 1
print("\r[{0}] Reading file '{1}'[{2:>3.1%}] ".format(printinfo, filename, sent_count/len(sentences)), end='')
return _nnp, words
Основной код:
dictionary = dict()
nnp = set()
# Initialize tagger and stemmer
pos_tagger = nltk.tag.PerceptronTagger()
ps = nltk.PorterStemmer()
stopwords = nltk.corpus.stopwords.words('english')
file_count = 0
# For each file, extract words and named entities
for file in files:
file_count += 1
_nnp, _dictionary = process_file(open(file, 'r', encoding='utf-8'), pos_tagger, ps, stopwords, file, str(file_count)+"/"+str(len(files)))
# Extend dictionary
for word in _dictionary.keys():
if word in dictionary.keys():
dictionary[word] += _dictionary[word]
else:
dictionary[word] = _dictionary[word]
# Join sets
nnp = nnp.union(_nnp)
end = time.time()
print("COMPLETED: Step 2 completed in {0:.3f}s".format(end-start))
Вот пример того, как может выглядеть текст:
In slow motion, afraid of what he was about to witness, Langdon rotated the fax 180 degrees. He looked at the word upside down.
Instantly, the breath went out of him. It was like he had been hit by a truck. Barely able to believe his eyes, he rotated the fax again, reading the brand right-side up and then upside down.
"Illuminati," he whispered.