JL i;~dZddlZddlZddlmZgdgdgddZedd d Zed d dZdZ dZ d#dZ ejjfdZdZdZd$dZd%dZd&dZdZd'dZd(dZdZd)dZdZdZed k(r9ddlZdd!lmZed"ed"eeeeyy)*a Code for extracting relational triples from the ieer and conll2002 corpora. Relations are stored internally as dictionaries ('reldicts'). The two serialization outputs are "rtuple" and "clause". - An rtuple is a tuple of the form ``(subj, filler, obj)``, where ``subj`` and ``obj`` are pairs of Named Entity mentions, and ``filler`` is the string of words occurring between ``sub`` and ``obj`` (with no intervening NEs). Strings are printed via ``repr()`` to circumvent locale variations in rendering utf-8 encoded strings. - A clause is an atom of the form ``relsym(subjsym, objsym)``, where the relation, subject and object have been canonicalized to single strings. N) defaultdict) LOCATION ORGANIZATIONPERSONDURATIONDATECARDINALPERCENTMONEYMEASURE)LOCPERORG) rrrrrr r r r FACILITYGPE)ieer conll2002acerrr)r rrr rr)rrrc8 t|S#t$r|cYSwxYw)zF Expand an NE class name. :type type: str :rtype: str ) short2longKeyErrortypes Y/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/sem/relextract.py_expandr?& $    c8 t|S#t$r|cYSwxYw)zJ Abbreviate an NE class name. :type type: str :rtype: str ) long2shortrrs r class_abbrevr Krrc |j|S#t$r?|r|jd|DcYSddlm|jfd|DcYSwxYw)z Join a list into a string, turning tags tuples into tag strings or just words. :param untag: if ``True``, omit the tag from tagged input strings. :type lst: list :rtype: str c3&K|] }|d yw)rN).0tups r z_join..bs2sCF2sr) tuple2strc3.K|] }|yw)Nr#)r$r%r's rr&z_join..es63 #6s)join TypeErrornltk.tagr')lstsepuntagr's @r_joinr/WsU7xx} 7 882c22 2&xx6#666 7s#A AAcl ||jdS#t$r|jdcYSwxYw)z` Translate one entity to its ISO Latin value. Inspired by example from effbot.org r)groupr)mdefss rdescape_entityr5hs7AGGAJ wwqzs 33ct|dd}|j}tjd}|j t |}|j dd}|S)z Convert a list of strings into a canonical symbol. :type lst: list :return: a Unicode string without whitespace :rtype: unicode _Tr.z&(\w+?);.)r/lowerrecompilesubr5replace)r,symENTs rlist2symrBvsP S %C ))+C **[ !C ''.# &C ++c2 C Jcddlm}g}gdg}|D]=}t||s|dj|$||d<|j|gdg}?|S)a Group a chunk structure into a list of 'semi-relations' of the form (list(str), ``Tree``). In order to facilitate the construction of (``Tree``, string, ``Tree``) triples, this identifies pairs whose first member is a list (possibly empty) of terminal strings, and whose second member is a ``Tree`` of the form (NE_label, terminals). :param tree: a chunk tree :return: a list of pairs (list(str), ``Tree``) :rtype: list of tuple rTreeNr1) nltk.treerF isinstanceappend)treerF semi_relssemi_reldtrs r tree2semi_relrNsjIDzH"#t$ QK  s #HQK   X &DzH" rCc g}t|dkDrhtt}t|dd| d|d<|ddj |d<t|ddj |d<t |ddj |d<t|dd|d <t|ddd |d <|ddj |d <t|ddj |d<t |ddj |d<t|ddd||d<|rtd|d d|dd|d d|j||dd}t|dkDrh|S)a Converts the pairs generated by ``tree2semi_rel`` into a 'reldict': a dictionary which stores information about the subject and object NEs plus the filler between them. Additionally, a left and right context of length =< window are captured (within a given input sentence). :param pairs: a pair of list(str) and ``Tree``, as generated by :param window: a threshold for the number of items to include in the left and right context :type window: int :return: 'relation' dictionaries whose keys are 'lcon', 'subjclass', 'subjtext', 'subjsym', 'filler', objclass', objtext', 'objsym' and 'rcon' :rtype: list(defaultdict) rNlconr1 subjclasssubjtextsubjsymfillerTr8untagged_fillerobjclassobjtextobjsymrcon(z, )) lenrstrr/labelleavesrBprintrI)pairswindowtraceresultreldicts rsemi_rel2reldictrgsF e*q.c"a VGH 56$Qx{002 #E!HQK$6$6$89 %eAhqk&8&8&:; !%(1+.%*58A;d%C!"#Ahqk//1 "58A;#5#5#78 $U1Xa[%7%7%9:a GV 45  -.K(J'    gab - e*q.. MrCcr9t|vr.tt|vr tntdzr9t|vr.tt|vr tntdz|dk(s|dk(r t|}n<|dk(r,t|jt|j z}n tdt |}fd}tt||S)a Filter the output of ``semi_rel2reldict`` according to specified NE classes and a filler pattern. The parameters ``subjclass`` and ``objclass`` can be used to restrict the Named Entities to particular types (any of 'LOCATION', 'ORGANIZATION', 'PERSON', 'DURATION', 'DATE', 'CARDINAL', 'PERCENT', 'MONEY', 'MEASURE'). :param subjclass: the class of the subject Named Entity. :type subjclass: str :param objclass: the class of the object Named Entity. :type objclass: str :param doc: input document :type doc: ieer document or a list of chunk trees :param corpus: name of the corpus to take as input; possible values are 'ieer' and 'conll2002' :type corpus: str :param pattern: a regular expression for filtering the fillers of retrieved triples. :type pattern: SRE_Pattern :param window: filters out fillers which exceed this threshold :type window: int :return: see ``mk_reldicts`` :rtype: list(defaultdict) z;your value for the subject type has not been recognized: %sz:your value for the object type has not been recognized: %srrrzcorpus type not recognizedc|dk(xr?t|djkxrj|dxr|dk(S)NrRrUrW)r]splitmatch)xrWpatternrRrcs rzextract_rels..s[ +)# & ( !!# $ . & MM!H+ & & jMX % rC) NE_CLASSESr ValueErrorrNtextheadlinerglistfilter) rRrWdoccorpusrmrcrbreldicts relfilters `` `` r extract_relsrys4Yj&88 9 F!3 3 *IM HJv$66 8  6 2 2x(HLxW &K/c" 6 chh'- *EE566&HI y(+ ,,rCct|d|d|dt|d|dg}d}|r|dg|z}d|z}|r|j|d |d z}t|}||zS) zy Pretty print the reldict as an rtuple. :param reldict: a relation dictionary :type reldict: defaultdict rRrSrUrWrXz[%s: %r] %r [%s: %r]rQz...%r)rZz(%r...)r rItuple)rfrQrZitemsformat printargss rrtuplers W[)* WZ()   E$F !E)F"  WV_%("e I I rCc"||d|df}d|zS)z Print the relation in clausal form. :param reldict: a relation dictionary :type reldict: defaultdict :param relsym: a label for the relation :type relsym: str rTrYz %s(%r, %r)r#)rfrelsymr|s rclausers%WY'): ;E % rCc fddlm}|r7 ddl}|jd}|j }|j dtjd}ttdtd |jD]}|j|D]} |r t| jtd td d | d |D]S} tt!| d|s | d| d| jf} j d| j#U|rE j dttdtd|D] } t| yy#t $rddl}|jdYQwxYw#t$$rYwxYw#t$$rYywxYw)a. Select pairs of organizations and locations whose mentions occur with an intervening occurrence of the preposition "in". If the sql parameter is set to True, then the entity pairs are loaded into an in-memory database, and subsequently pulled out using an SQL "SELECT" query. rrNz:memory:zPcreate table Locations (OrgName text, LocationName text, DocID text)z/Cannot import sqlite; sql flag will be ignored.z.*\bin\b(?!\b.+ing)z'IEER: in(ORG, LOC) -- just the clauses:-============================================================rr rrvrmINrrSrXzJinsert into Locations values (?, ?, ?)zTselect OrgName from Locations where LocationName = 'Atlanta'z,Extract data from SQL table: ORGs in Atlantaz---------------) nltk.corpusrsqlite3connectcursorexecute ImportErrorwarningswarnr<r=rafileids parsed_docsdocnoryrcommit NameError) rdsqlrr connectioncurrrfilerurelrrows rin_demor3s!  M  4J##%C KK=  * +B G 34 (O ##D) Ccii h#E5#fbQ fS./ "%j/3y>399!M 8" #))+   &   KK:  G @ A (O c   = M  MMK L M6%   s66E0+7F+AF$0FF F! F! $ F0/F0c ddlm}d}tj|tj}t t dt d|j D]n}|j|D]X}dx}}|r$t |jt ddx}}td d |d | D]}t t||| Zpy)Nrra (.*( # assorted roles analyst| chair(wo)?man| commissioner| counsel| director| economist| editor| executive| foreman| governor| head| lawyer| leader| librarian).*)| manager| partner| president| producer| professor| researcher| spokes(wo)?man| writer| ,\sof\sthe?\s* # "X, of (the) Y" z(IEER: has_role(PER, ORG) -- raw rtuples:rFrTrrrrrQrZ) rrr<r=VERBOSErarrrryr) rdrrolesROLESrrurQrZrs r roles_demorzs  E4 JJubjj )E G 45 (O 9##D) 9C D4cii h""t#E5#feT 9fSt$78 9  99rCc.ddlm}ddlm}t dt d|j Dcgc]0}|j |D]}|j|jf2}}}|ddD]}t t d|zycc}}w)NrrrEzIEER: First 20 Headlinesrz%s: %s) rrrGrFrarrrrr)rrFrrutreesrJs rieer_headlinesrs  $% (OLLN  ##D)   CLL! ! E  cr    i$  s5Bc 6ddlm}d}tj|tj}t t dt d|j dD]9}dx}}|rdx}}td d |d |d D]}t t|||;y)zh Find the copula+'van' relation ('of') in the Dutch tagged training corpus from CoNLL 2002. rrz ( is/V| # 3rd sing present and was/V| # past forms of the verb zijn ('be') werd/V| # and also present wordt/V # past of worden ('become) ) .* # followed by anything van/Prep # followed by van ('of') z;Dutch CoNLL2002: van(PER, ORG) -- raw rtuples with context:rz ned.trainFTrrr rvrmrcrN) rrr<r=rra chunked_sentsryr)rdrvnvVANrurQrZrs rconllnedrs & C **S"** %C G GH (O&&{35t  D4 5#k3r  5C &4d3 4 5 5rCc fddlm}d}tj|tj}t t dt d|j dDcgc]}tdd|d | D]}|}}}|dd D]}t t|d t ycc}}w)Nrrz. .* ( de/SP| del/SP ) z=Spanish CoNLL2002: de(ORG, LOC) -- just the first 10 clauses:rz esp.trainrr rrrDEr) rrr<r=rrarryr)rderrurrelsrs rconllesprs% B B #B G IJ (O**;7  uc+rR      D  #2Y& fQt$%& G s!B-c vttdtdtjd}g}ttj j jddD]K\}}t j|}tdd|d|d }|D]}t|d t|My) NzB1500 Sentences from Penn Treebank, as processed by NLTK NE ChunkerrzC.*(chairman|president|trader|scientist|economist|analyst|partner).*irrrrz<5) rar<r= enumeratenltkrvtreebank tagged_sentsne_chunkryr)ROLErisentrs r ne_chunkedrs G NO (O ::N D DT[[11>>@$GH*4}}T"E5$udSTU *C QrF6#;-( ) **rC__main__) relextract)rd) F)F)rNr)FF)rT)r)r1)__doc__htmlr< collectionsrrodictrrrr r/entities entitydefsr5rBrNrgryrrrrrrrr__name__rnltk.semrr#rCrrs " # '  :jn( C 5uU C   7" ==33  :%P:-z0  (?N+9f ,5N 2 * z# !Q J JLrC