Example
"""
Description: Named Entity Recognition API usage example.
Copyright: (C) 2016 EffectiveSoft Ltd. All Rights Reserved.
Technical support: technical-support@effective-soft.com
"""
import json
import urllib
import urllib2
# possible named entities types
ners = ["Unknown", "Person", "Organization", "Location", "Title", "Position", "Age", \
"Date", "Duration", "Nationality", "Event", "Url", "MiscellaneousLocation"]
# sample text
sample_text = "Eyal Shaked was appointed General Manager of the Optical Networks Division in October 2005."
# set the URL for POST request and specify API key for authorization purposes (change YourAPIKey to the Intellexer API key)
api_url = "http://api.intellexer.com/recognizeNeText?apikey=YourAPIKey&loadNamedEntities=true&loadRelationsTree=true&loadSentences=true"
# print relations tree
def print_tree(node, height):
for i in range(0, height):
print "\t",
print node.get('text')
children = node.get('children')
height += 1
for child in children:
print_tree(child, height)
# print information about detected named entities
def print_response(response):
print "Detected Named Entities:"
entities = response.get('entities')
for entity in entities:
print "\t", ners[entity.get('type')], ": ", entity.get('text')
# print relations tree
print "Relations tree:";
print_tree(response.get('relationsTree'), 1)
# create request to the Named Entity Recognition API service
def request_api(url, text):
header = { 'Content-Type' : "application/octet-stream" }
req = urllib2.Request(url, text, header)
conn = urllib2.urlopen(req)
try:
json_response = json.loads(conn.read())
finally:
conn.close()
print_response(json_response)
# perform the request
try:
request_api(api_url, sample_text)
except urllib2.HTTPError as error:
print 'HTTP error - %s' % error.read()
Output
Detected Named Entities:
Person : Eyal Shaked
Organization : Optical Networks Division
Position : General Manager
Date : October 2005
Relations tree:
root: Relations
NE-person: Eyal Shaked
VP: appointed (O-V)
NE-pos: General Manager (POS)
NE-org: Optical Networks Division (of)
NE-date: October 2005 (DATE)