Created
July 19, 2018 02:58
-
-
Save pilgrim2go/74ecfa19fce0b4fd0f48fbda87e9684e to your computer and use it in GitHub Desktop.
Extract entities using NLTK
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/36255291/extract-city-names-from-text-using-python | |
import nltk | |
def extract_entity_names(t): | |
entity_names = [] | |
if hasattr(t, 'label') and t.label: | |
if t.label() == 'NE': | |
entity_names.append(' '.join([child[0] for child in t])) | |
else: | |
for child in t: | |
entity_names.extend(extract_entity_names(child)) | |
return entity_names | |
with open('sample2.txt', 'r') as f: | |
for line in f: | |
sentences = nltk.sent_tokenize(line) | |
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences] | |
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences] | |
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True) | |
entities = [] | |
for tree in chunked_sentences: | |
entities.extend(extract_entity_names(tree)) | |
print(entities) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment