relextract.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. # Natural Language Toolkit: Relation Extraction
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Ewan Klein <ewan@inf.ed.ac.uk>
  5. # URL: <http://nltk.org/>
  6. # For license information, see LICENSE.TXT
  7. """
  8. Code for extracting relational triples from the ieer and conll2002 corpora.
  9. Relations are stored internally as dictionaries ('reldicts').
  10. The two serialization outputs are "rtuple" and "clause".
  11. - An rtuple is a tuple of the form ``(subj, filler, obj)``,
  12. where ``subj`` and ``obj`` are pairs of Named Entity mentions, and ``filler`` is the string of words
  13. occurring between ``sub`` and ``obj`` (with no intervening NEs). Strings are printed via ``repr()`` to
  14. circumvent locale variations in rendering utf-8 encoded strings.
  15. - A clause is an atom of the form ``relsym(subjsym, objsym)``,
  16. where the relation, subject and object have been canonicalized to single strings.
  17. """
  18. # todo: get a more general solution to canonicalized symbols for clauses -- maybe use xmlcharrefs?
  19. from collections import defaultdict
  20. import html
  21. import re
  22. # Dictionary that associates corpora with NE classes
  23. NE_CLASSES = {
  24. "ieer": [
  25. "LOCATION",
  26. "ORGANIZATION",
  27. "PERSON",
  28. "DURATION",
  29. "DATE",
  30. "CARDINAL",
  31. "PERCENT",
  32. "MONEY",
  33. "MEASURE",
  34. ],
  35. "conll2002": ["LOC", "PER", "ORG"],
  36. "ace": [
  37. "LOCATION",
  38. "ORGANIZATION",
  39. "PERSON",
  40. "DURATION",
  41. "DATE",
  42. "CARDINAL",
  43. "PERCENT",
  44. "MONEY",
  45. "MEASURE",
  46. "FACILITY",
  47. "GPE",
  48. ],
  49. }
  50. # Allow abbreviated class labels
  51. short2long = dict(LOC="LOCATION", ORG="ORGANIZATION", PER="PERSON")
  52. long2short = dict(LOCATION="LOC", ORGANIZATION="ORG", PERSON="PER")
  53. def _expand(type):
  54. """
  55. Expand an NE class name.
  56. :type type: str
  57. :rtype: str
  58. """
  59. try:
  60. return short2long[type]
  61. except KeyError:
  62. return type
  63. def class_abbrev(type):
  64. """
  65. Abbreviate an NE class name.
  66. :type type: str
  67. :rtype: str
  68. """
  69. try:
  70. return long2short[type]
  71. except KeyError:
  72. return type
  73. def _join(lst, sep=" ", untag=False):
  74. """
  75. Join a list into a string, turning tags tuples into tag strings or just words.
  76. :param untag: if ``True``, omit the tag from tagged input strings.
  77. :type lst: list
  78. :rtype: str
  79. """
  80. try:
  81. return sep.join(lst)
  82. except TypeError:
  83. if untag:
  84. return sep.join(tup[0] for tup in lst)
  85. from nltk.tag import tuple2str
  86. return sep.join(tuple2str(tup) for tup in lst)
  87. def descape_entity(m, defs=html.entities.entitydefs):
  88. """
  89. Translate one entity to its ISO Latin value.
  90. Inspired by example from effbot.org
  91. """
  92. try:
  93. return defs[m.group(1)]
  94. except KeyError:
  95. return m.group(0) # use as is
  96. def list2sym(lst):
  97. """
  98. Convert a list of strings into a canonical symbol.
  99. :type lst: list
  100. :return: a Unicode string without whitespace
  101. :rtype: unicode
  102. """
  103. sym = _join(lst, "_", untag=True)
  104. sym = sym.lower()
  105. ENT = re.compile("&(\w+?);")
  106. sym = ENT.sub(descape_entity, sym)
  107. sym = sym.replace(".", "")
  108. return sym
  109. def tree2semi_rel(tree):
  110. """
  111. Group a chunk structure into a list of 'semi-relations' of the form (list(str), ``Tree``).
  112. In order to facilitate the construction of (``Tree``, string, ``Tree``) triples, this
  113. identifies pairs whose first member is a list (possibly empty) of terminal
  114. strings, and whose second member is a ``Tree`` of the form (NE_label, terminals).
  115. :param tree: a chunk tree
  116. :return: a list of pairs (list(str), ``Tree``)
  117. :rtype: list of tuple
  118. """
  119. from nltk.tree import Tree
  120. semi_rels = []
  121. semi_rel = [[], None]
  122. for dtr in tree:
  123. if not isinstance(dtr, Tree):
  124. semi_rel[0].append(dtr)
  125. else:
  126. # dtr is a Tree
  127. semi_rel[1] = dtr
  128. semi_rels.append(semi_rel)
  129. semi_rel = [[], None]
  130. return semi_rels
  131. def semi_rel2reldict(pairs, window=5, trace=False):
  132. """
  133. Converts the pairs generated by ``tree2semi_rel`` into a 'reldict': a dictionary which
  134. stores information about the subject and object NEs plus the filler between them.
  135. Additionally, a left and right context of length =< window are captured (within
  136. a given input sentence).
  137. :param pairs: a pair of list(str) and ``Tree``, as generated by
  138. :param window: a threshold for the number of items to include in the left and right context
  139. :type window: int
  140. :return: 'relation' dictionaries whose keys are 'lcon', 'subjclass', 'subjtext', 'subjsym', 'filler', objclass', objtext', 'objsym' and 'rcon'
  141. :rtype: list(defaultdict)
  142. """
  143. result = []
  144. while len(pairs) > 2:
  145. reldict = defaultdict(str)
  146. reldict["lcon"] = _join(pairs[0][0][-window:])
  147. reldict["subjclass"] = pairs[0][1].label()
  148. reldict["subjtext"] = _join(pairs[0][1].leaves())
  149. reldict["subjsym"] = list2sym(pairs[0][1].leaves())
  150. reldict["filler"] = _join(pairs[1][0])
  151. reldict["untagged_filler"] = _join(pairs[1][0], untag=True)
  152. reldict["objclass"] = pairs[1][1].label()
  153. reldict["objtext"] = _join(pairs[1][1].leaves())
  154. reldict["objsym"] = list2sym(pairs[1][1].leaves())
  155. reldict["rcon"] = _join(pairs[2][0][:window])
  156. if trace:
  157. print(
  158. "(%s(%s, %s)"
  159. % (
  160. reldict["untagged_filler"],
  161. reldict["subjclass"],
  162. reldict["objclass"],
  163. )
  164. )
  165. result.append(reldict)
  166. pairs = pairs[1:]
  167. return result
  168. def extract_rels(subjclass, objclass, doc, corpus="ace", pattern=None, window=10):
  169. """
  170. Filter the output of ``semi_rel2reldict`` according to specified NE classes and a filler pattern.
  171. The parameters ``subjclass`` and ``objclass`` can be used to restrict the
  172. Named Entities to particular types (any of 'LOCATION', 'ORGANIZATION',
  173. 'PERSON', 'DURATION', 'DATE', 'CARDINAL', 'PERCENT', 'MONEY', 'MEASURE').
  174. :param subjclass: the class of the subject Named Entity.
  175. :type subjclass: str
  176. :param objclass: the class of the object Named Entity.
  177. :type objclass: str
  178. :param doc: input document
  179. :type doc: ieer document or a list of chunk trees
  180. :param corpus: name of the corpus to take as input; possible values are
  181. 'ieer' and 'conll2002'
  182. :type corpus: str
  183. :param pattern: a regular expression for filtering the fillers of
  184. retrieved triples.
  185. :type pattern: SRE_Pattern
  186. :param window: filters out fillers which exceed this threshold
  187. :type window: int
  188. :return: see ``mk_reldicts``
  189. :rtype: list(defaultdict)
  190. """
  191. if subjclass and subjclass not in NE_CLASSES[corpus]:
  192. if _expand(subjclass) in NE_CLASSES[corpus]:
  193. subjclass = _expand(subjclass)
  194. else:
  195. raise ValueError(
  196. "your value for the subject type has not been recognized: %s"
  197. % subjclass
  198. )
  199. if objclass and objclass not in NE_CLASSES[corpus]:
  200. if _expand(objclass) in NE_CLASSES[corpus]:
  201. objclass = _expand(objclass)
  202. else:
  203. raise ValueError(
  204. "your value for the object type has not been recognized: %s" % objclass
  205. )
  206. if corpus == "ace" or corpus == "conll2002":
  207. pairs = tree2semi_rel(doc)
  208. elif corpus == "ieer":
  209. pairs = tree2semi_rel(doc.text) + tree2semi_rel(doc.headline)
  210. else:
  211. raise ValueError("corpus type not recognized")
  212. reldicts = semi_rel2reldict(pairs)
  213. relfilter = lambda x: (
  214. x["subjclass"] == subjclass
  215. and len(x["filler"].split()) <= window
  216. and pattern.match(x["filler"])
  217. and x["objclass"] == objclass
  218. )
  219. return list(filter(relfilter, reldicts))
  220. def rtuple(reldict, lcon=False, rcon=False):
  221. """
  222. Pretty print the reldict as an rtuple.
  223. :param reldict: a relation dictionary
  224. :type reldict: defaultdict
  225. """
  226. items = [
  227. class_abbrev(reldict["subjclass"]),
  228. reldict["subjtext"],
  229. reldict["filler"],
  230. class_abbrev(reldict["objclass"]),
  231. reldict["objtext"],
  232. ]
  233. format = "[%s: %r] %r [%s: %r]"
  234. if lcon:
  235. items = [reldict["lcon"]] + items
  236. format = "...%r)" + format
  237. if rcon:
  238. items.append(reldict["rcon"])
  239. format = format + "(%r..."
  240. printargs = tuple(items)
  241. return format % printargs
  242. def clause(reldict, relsym):
  243. """
  244. Print the relation in clausal form.
  245. :param reldict: a relation dictionary
  246. :type reldict: defaultdict
  247. :param relsym: a label for the relation
  248. :type relsym: str
  249. """
  250. items = (relsym, reldict["subjsym"], reldict["objsym"])
  251. return "%s(%r, %r)" % items
  252. #######################################################
  253. # Demos of relation extraction with regular expressions
  254. #######################################################
  255. ############################################
  256. # Example of in(ORG, LOC)
  257. ############################################
  258. def in_demo(trace=0, sql=True):
  259. """
  260. Select pairs of organizations and locations whose mentions occur with an
  261. intervening occurrence of the preposition "in".
  262. If the sql parameter is set to True, then the entity pairs are loaded into
  263. an in-memory database, and subsequently pulled out using an SQL "SELECT"
  264. query.
  265. """
  266. from nltk.corpus import ieer
  267. if sql:
  268. try:
  269. import sqlite3
  270. connection = sqlite3.connect(":memory:")
  271. connection.text_factory = sqlite3.OptimizedUnicode
  272. cur = connection.cursor()
  273. cur.execute(
  274. """create table Locations
  275. (OrgName text, LocationName text, DocID text)"""
  276. )
  277. except ImportError:
  278. import warnings
  279. warnings.warn("Cannot import sqlite; sql flag will be ignored.")
  280. IN = re.compile(r".*\bin\b(?!\b.+ing)")
  281. print()
  282. print("IEER: in(ORG, LOC) -- just the clauses:")
  283. print("=" * 45)
  284. for file in ieer.fileids():
  285. for doc in ieer.parsed_docs(file):
  286. if trace:
  287. print(doc.docno)
  288. print("=" * 15)
  289. for rel in extract_rels("ORG", "LOC", doc, corpus="ieer", pattern=IN):
  290. print(clause(rel, relsym="IN"))
  291. if sql:
  292. try:
  293. rtuple = (rel["subjtext"], rel["objtext"], doc.docno)
  294. cur.execute(
  295. """insert into Locations
  296. values (?, ?, ?)""",
  297. rtuple,
  298. )
  299. connection.commit()
  300. except NameError:
  301. pass
  302. if sql:
  303. try:
  304. cur.execute(
  305. """select OrgName from Locations
  306. where LocationName = 'Atlanta'"""
  307. )
  308. print()
  309. print("Extract data from SQL table: ORGs in Atlanta")
  310. print("-" * 15)
  311. for row in cur:
  312. print(row)
  313. except NameError:
  314. pass
  315. ############################################
  316. # Example of has_role(PER, LOC)
  317. ############################################
  318. def roles_demo(trace=0):
  319. from nltk.corpus import ieer
  320. roles = """
  321. (.*( # assorted roles
  322. analyst|
  323. chair(wo)?man|
  324. commissioner|
  325. counsel|
  326. director|
  327. economist|
  328. editor|
  329. executive|
  330. foreman|
  331. governor|
  332. head|
  333. lawyer|
  334. leader|
  335. librarian).*)|
  336. manager|
  337. partner|
  338. president|
  339. producer|
  340. professor|
  341. researcher|
  342. spokes(wo)?man|
  343. writer|
  344. ,\sof\sthe?\s* # "X, of (the) Y"
  345. """
  346. ROLES = re.compile(roles, re.VERBOSE)
  347. print()
  348. print("IEER: has_role(PER, ORG) -- raw rtuples:")
  349. print("=" * 45)
  350. for file in ieer.fileids():
  351. for doc in ieer.parsed_docs(file):
  352. lcon = rcon = False
  353. if trace:
  354. print(doc.docno)
  355. print("=" * 15)
  356. lcon = rcon = True
  357. for rel in extract_rels("PER", "ORG", doc, corpus="ieer", pattern=ROLES):
  358. print(rtuple(rel, lcon=lcon, rcon=rcon))
  359. ##############################################
  360. ### Show what's in the IEER Headlines
  361. ##############################################
  362. def ieer_headlines():
  363. from nltk.corpus import ieer
  364. from nltk.tree import Tree
  365. print("IEER: First 20 Headlines")
  366. print("=" * 45)
  367. trees = [
  368. (doc.docno, doc.headline)
  369. for file in ieer.fileids()
  370. for doc in ieer.parsed_docs(file)
  371. ]
  372. for tree in trees[:20]:
  373. print()
  374. print("%s:\n%s" % tree)
  375. #############################################
  376. ## Dutch CONLL2002: take_on_role(PER, ORG
  377. #############################################
  378. def conllned(trace=1):
  379. """
  380. Find the copula+'van' relation ('of') in the Dutch tagged training corpus
  381. from CoNLL 2002.
  382. """
  383. from nltk.corpus import conll2002
  384. vnv = """
  385. (
  386. is/V| # 3rd sing present and
  387. was/V| # past forms of the verb zijn ('be')
  388. werd/V| # and also present
  389. wordt/V # past of worden ('become)
  390. )
  391. .* # followed by anything
  392. van/Prep # followed by van ('of')
  393. """
  394. VAN = re.compile(vnv, re.VERBOSE)
  395. print()
  396. print("Dutch CoNLL2002: van(PER, ORG) -- raw rtuples with context:")
  397. print("=" * 45)
  398. for doc in conll2002.chunked_sents("ned.train"):
  399. lcon = rcon = False
  400. if trace:
  401. lcon = rcon = True
  402. for rel in extract_rels(
  403. "PER", "ORG", doc, corpus="conll2002", pattern=VAN, window=10
  404. ):
  405. print(rtuple(rel, lcon=lcon, rcon=rcon))
  406. #############################################
  407. ## Spanish CONLL2002: (PER, ORG)
  408. #############################################
  409. def conllesp():
  410. from nltk.corpus import conll2002
  411. de = """
  412. .*
  413. (
  414. de/SP|
  415. del/SP
  416. )
  417. """
  418. DE = re.compile(de, re.VERBOSE)
  419. print()
  420. print("Spanish CoNLL2002: de(ORG, LOC) -- just the first 10 clauses:")
  421. print("=" * 45)
  422. rels = [
  423. rel
  424. for doc in conll2002.chunked_sents("esp.train")
  425. for rel in extract_rels("ORG", "LOC", doc, corpus="conll2002", pattern=DE)
  426. ]
  427. for r in rels[:10]:
  428. print(clause(r, relsym="DE"))
  429. print()
  430. def ne_chunked():
  431. print()
  432. print("1500 Sentences from Penn Treebank, as processed by NLTK NE Chunker")
  433. print("=" * 45)
  434. ROLE = re.compile(
  435. r".*(chairman|president|trader|scientist|economist|analyst|partner).*"
  436. )
  437. rels = []
  438. for i, sent in enumerate(nltk.corpus.treebank.tagged_sents()[:1500]):
  439. sent = nltk.ne_chunk(sent)
  440. rels = extract_rels("PER", "ORG", sent, corpus="ace", pattern=ROLE, window=7)
  441. for rel in rels:
  442. print("{0:<5}{1}".format(i, rtuple(rel)))
  443. if __name__ == "__main__":
  444. import nltk
  445. from nltk.sem import relextract
  446. in_demo(trace=0)
  447. roles_demo(trace=0)
  448. conllned()
  449. conllesp()
  450. ieer_headlines()
  451. ne_chunked()