-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPETRtree.py
1797 lines (1507 loc) · 63 KB
/
PETRtree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
from __future__ import print_function
from __future__ import unicode_literals
import PETRglobals
import PETRreader
import time
import utilities
import types
import logging
# -- from inspect import getouterframes, currentframe # -- # used to track the levels of recursion
# PETRtree.py
# Author: Clayton Norris
# Caerus Associates/ University of Chicago
#
#
# Purpose:
# Called from petrarch.py, this contains the main logic
# of the Petrarch software. Sentences are stored into
# Sentence class objects, which contain a tree of Phrase
# class objects. The phrases then do analyses of their role
# in the sentence and the event information of the overall sentence
# is calculated and returned within the get_events() method
#
#
# Revision history:
# July 2015 - Created
# August 2015 - First release
# April 2016 - Bugs causing crashes in very low frequency cases corrected
# pas 16.04.22: print() statements commented-out with '# --' were used in
# the debugging and can probably be removed
class Phrase:
"""
This is a general class for all Phrase instances, which make up the nodes in the syntactic tree.
The three subtypes are below.
"""
def __init__(self, label, date, sentence):
"""
Initialization for Phrase classes.
Parameters
-----------
label: list
Label for the phrase type, date
Returns
-------
An instantiated Phrase object
"""
self.label = label if not label == "MD" else "VB"
self.children = []
self.phrasetype = label[0]
self.annotation = ""
self.text = ""
self.parent = None
self.meaning = ""
self.verbclass = ""
self.date = date
self.index = -1
self.head = None
self.head_phrase = None
self.color = False
self.sentence = sentence
def get_meaning(self):
"""
Method for returning the meaning of the subtree rooted by this phrase,
is overwritten by all subclasses, so this works primarily for
S and S-Bar phrases.
Parameters
-----------
self: Phrase object that called the method
Returns
-------
events: list
Combined meanings of the phrases children
"""
if self.label in "SBAR":
lower = map(
lambda b: b.get_meaning(),
filter(
lambda a: a.label in "SBARVP",
self.children))
events = []
for item in lower:
events += item
if events:
self.meaning = events
return events
return self.meaning
def get_text(self):
if self.color:
return ""
text = self.text
for child in self.children:
if isinstance(child, NounPhrase):
text += " " + child.get_text()[0]
else:
text += " " + child.get_text()
return text
def get_parse_text(self):
""" This is a fairly specific debugging function: to recover the original parse,
use indented_parse_print(self, level=0) or get_parse_string(self) """
if self.color:
return ""
text = self.text
for child in self.children:
if isinstance(child, NounPhrase):
text += "(NP " + child.get_text()[0] + ")"
elif isinstance(child, VerbPhrase):
text += "(VP " + child.get_text() + ")"
else:
text += "(XP " + child.get_text() + ")"
return text
def indented_parse_print(self, level=0):
""" recursive print of labeled phrase elements and children with line feeds and indentation """
print(' ' * level + '(' + self.label + ' ' + self.text, end='')
for child in self.children:
child.indented_parse_print(level + 1)
print(' ' * level + ')')
def get_parse_string(self):
""" recursive rendering of labelled phrase element and children as a string:
when called from ROOT it returns the original input string """
text = '(' + self.label
if self.text:
text += ' ' + self.text
for child in self.children:
text += ' ' + child.get_parse_string()
text += ')'
return text
def resolve_codes(self, codes):
"""
Method that divides a list of mixed codes into actor and agent codes
Parameters
-----------
codes: list
Mixed list of codes
Returns
-------
actorcodes: list
List of actor codes
agentcodes: list
List of actor codes
"""
if not codes:
return [], []
actorcodes = []
agentcodes = []
for code in codes:
if not code:
continue
if code.startswith("~"):
agentcodes.append(code)
else:
actorcodes.append(code)
return actorcodes, agentcodes
def mix_codes(self, agents, actors):
"""
Combine the actor codes and agent codes addressing duplicates
and removing the general "~PPL" if there's a better option.
Parameters
-----------
agents, actors : Lists of their respective codes
Returns
-------
codes: list
[Agent codes] x [Actor codes]
"""
# -- print('mc-entry',actors,agents)
codes = set()
mix = lambda a, b: a + b if not b in a else a
actors = actors if actors else ['~']
for ag in agents:
if ag == '~PPL' and len(agents) > 1:
continue
# actors = map( lambda a : mix( a[0], ag[1:]), actors)
actors = map(lambda a: mix(a, ag[1:]), actors)
# -- print('mc-1',actors)
return filter(lambda a: a not in ['', '~', '~~', None], actors)
# 16.04.25 hmmm, this is either a construct of utterly phenomenal
# subtlety or else we never hit this code...
codes = set()
# -- print('WTF-1')
for act in (actors if actors else ['~']):
for ag in (agents if agents else ['~']):
if ag == "~PPL" and len(agents) > 1:
continue
code = act
if not ag[1:] in act:
code += ag[1:]
if not code in ['~', '~~', ""]:
codes.add(code)
return list(codes)
def return_head(self):
return self.head, self.head_phrase
def get_head(self):
"""
Method for finding the head of a phrase. The head of a phrase is the rightmost
word-level constituent such that the path from root to head consists only of similarly-labeled
phrases.
Parameters
-----------
self: Phrase object that called the method
Returns
-------
possibilities[-1]: tuple (string,NounPhrase)
(The text of the head of the phrase, the NounPhrase object whose rightmost child is the
head).
"""
self.get_head = self.return_head
try:
if self.label == 'S':
self.head, self.head_phrase = map(
lambda b: b.get_head(), filter(
lambda a: a.label == 'VP', self.children))[0]
return (self.head, self.head_phrase)
elif self.label == 'ADVP':
return self.children[0].text, self
if (not self.label[1] == 'P'):
return (self.text, self.parent)
head_children = filter(
lambda child: child.label.startswith(
self.label[0]) and not child.label[1] == 'P',
self.children)
if head_children:
possibilities = filter(
None, map(
lambda a: a.get_head(), head_children))
else:
other_children = filter(
lambda child: child.label.startswith(
self.label[0]), self.children)
possibilities = filter(
None, map(
lambda a: a.get_head(), other_children))
self.head_phrase = possibilities[-1][1]
# return the last, English usually compounds words to the front
self.head = possibilities[-1][0]
return possibilities[-1]
except:
return (None, None)
def print_to_stdout(self, indent):
print(indent, self.label, self.text, self.get_meaning())
for child in self.children:
child.print_to_stdout(indent + "\t")
class NounPhrase(Phrase):
"""
Class specific to noun phrases.
Methods: get_meaning() - specific version of the super's method
check_date() - find the date-specific version of an actor
"""
def __init__(self, label, date, sentence):
Phrase.__init__(self, label, date, sentence)
def return_meaning(self):
return self.meaning
def get_text(self):
"""
Noun-specific get text method
"""
PPcodes = []
text = ""
for child in self.children:
if isinstance(child, PrepPhrase):
# -- print('NPgt-PP:',child.text) # --
m = self.resolve_codes(child.get_meaning())
if m[0]:
PPcodes += child.get_meaning()
else:
text += " " + child.get_text()
if isinstance(child, NounPhrase):
# -- print('NPgt-NP:',child.text) # --
value = child.get_text()
text += value[0]
PPcodes += value[1]
if child.label[:2] in ["JJ", "NN", "DT"]:
text += " " + child.text
return text, PPcodes
def check_date(self, match):
"""
Method for resolving date restrictions on actor codes.
Parameters
-----------
match: list
Dates and codes from the dictionary
Returns
-------
code: string
The code corresponding to how the actor should be coded given the date
Note <16.06.10 pas>
-------------------
In a very small set of cases involving a reflexive PRP inside a PP, the system can get into an infinite
recursion where it first backs up a couple levels from the (PP, then this call to child.get_meaning() drops
back down to the same point via the two child invocations in NounPhrase.get_meaning()
elif child.label == "PP":
m = self.resolve_codes(child.get_meaning())
and in PrepPhrase.get_meaning()
self.meaning = self.children[1].get_meaning() if isinstance(self.children[1],NounPhrase) else ""
which takes one back to the same point at one deeper level of recursion. These structures occurred about five times
in a 20M sentence corpus, and I couldn't find any fix that didn't break something else, so I just trapped it
here.
There are a bunch of commented-out debugging prints remaining from this futile pursuit that could presumably be
removed at some point.
The full record for one of the offending cases is:
<Sentence date = "20150824" id ="e35ef55a-fa30-4c34-baae-965dea33d8d8_3" source = "ANOTHER INFINITE RECURSION" sentence = "True">
<Text>
He started out at the bottom of the Hollywood rung, directed his own movie and managed to get noticed by Steven
Spielberg himself to nab a tiny role in 1998s Saving Private Ryan .
</Text>
<Parse>
(ROOT (S (S (NP (PRP He))
(VP (VBD started) (PRT (RP out))
(PP (IN at)
(NP (NP (DT the) (NN bottom))
(PP (IN of) (NP (DT the) (NNP Hollywood) ))))))
(VP (VBD rung))
(, ,)
(S (VP
(VP (VBD directed) (NP (PRP$ his) (JJ own) (NN movie))) (CC and)
(VP (VBD managed) (S
(VP (TO to)
(VP (VB get)
(VP (VBN noticed)
(PP (IN by)
(NP (NNP Steven) (NNP Spielberg) (PRP himself))
)
(S (VP (TO to) (VP (VB nab)
(NP (NP (DT a) (JJ tiny) (NN role))
(PP (IN in)
(NP (NP (NNS 1998s)) (VP (VBG Saving) (NP (JJ Private) (NNP Ryan))
))))))))))))))
(. .)))
</Parse>
</Sentence>
"""
code = None
try:
for j in match:
dates = j[1]
date = []
code = ""
for d in dates:
if d[0] in '<>':
date.append(d[0] +
str(PETRreader.dstr_to_ordate(d[1:])))
else:
date.append(str(PETRreader.dstr_to_ordate(d)))
curdate = self.date
if not date:
code = j[0]
elif len(date) == 1:
if date[0][0] == '<':
if curdate < int(date[0][1:]):
code = j[0]
else:
if curdate >= int(date[0][1:]):
code = j[0]
else:
if curdate < int(date[1]):
if curdate >= int(date[0]):
code = j[0]
if code:
return code
except Exception as e:
# print(e)
return code
return code
def get_meaning(self):
def recurse(path, words, length, so_far=""):
# -- print('NPgm-rec-lev:',len(getouterframes(currentframe(1)))) # --
if words and words[0] in path:
match = recurse(
path[
words[0]], words[
1:], length + 1, so_far + " " + words[0])
if match:
return match
if '#' in path:
if isinstance(path["#"], list):
code = self.check_date(path['#'])
if not code is None:
# -- print('NPgm-rec-1:',code) # --
# -- print('NPgm-rec-1.1:',path['#'][-1])
# 16.04.25 this branch always resolves to an actor;
# path['#'][-1] is the root string
return [code], so_far, length, [path['#'][-1]]
else:
# -- print('NPgm-rec-2:',path['#'])
# 16.04.25 this branch always resolves to an agent
return [path['#']], so_far, length
return False
text_children = []
PPcodes = []
VPcodes = []
NPcodes = []
codes = []
roots = []
# -- print('NPgm-0:') # --
matched_txt = []
for child in self.children:
if isinstance(child, NounPhrase):
# -- print('NPgm-NP:',child.text) # --
value = child.get_text()
text_children += value[0].split()
NPcodes += value[1]
elif child.label[:2] in ["JJ", "DT", "NN"]: # JJ:形容词或序数词 DT: 限定词 NN:名词 单数 第三人称单数 但是此处是label的前2个字符,表示比较级和最高级
text_children += child.get_text().split()
elif child.label == "PP":#介词短语
m = self.resolve_codes(child.get_meaning())
# -- print('NPgm-PP:',m) # --
if m[0]:
PPcodes += child.get_meaning()
else:
text_children += child.get_text().split()
elif child.label == "VP":
m = child.get_meaning()
if m and isinstance(m[0][1], basestring):
m = self.resolve_codes(m[0][1])
if m[0]:
VPcodes += child.get_theme()
else:
pass
# We could add the subtree here, but there shouldn't be
# any codes with VP components
elif child.label == "PRP":
# Find antecedent
# -- print('NPgm-PRP:',child.text) # --
not_found = True
level = self.parent
local = True
reflexive = child.text.endswith(
"SELF") or child.text.endswith("SELVES")
while not_found and level.parent:
if level.label.startswith(
"NP") and reflexive: # Intensive, ignore
# -- print('NPgm-1: Mk1') # --
break
if local and level.label in ["S", "SBAR"]:
# -- print('NPgm-1: Mk2') # --
local = False
level = level.parent
continue
if (not local) or (reflexive and local):
# -- print('NPgm-1: Mk3') # --
for child in level.parent.children:
if isinstance(child, NounPhrase):
try:
cgm = child.get_meaning() # see <16.06.10> note above
except:
break
# -- print('NPgm-1: Mk4',isinstance(child,NounPhrase),"'" + child.text + "'") # --
if not cgm == "~":
not_found = False
codes += child.get_meaning()
break
level = level.parent
# zhangshirong added begin
################################################################
if text_children:
PETRglobals.tmp_detail_text.append(tuple(text_children))
################################################################
# zhangshirong added end
# check whether there are codes in the noun Phrase
index = 0
while index < len(text_children):
match = recurse(
PETRglobals.ActorDict, text_children[
index:], 0) # checking for actors
if match:
# -- print('NPgm-m-1:',match)
codes += match[0]
roots += match[3]
index += match[2]
matched_txt += [match[1]]
continue
match = recurse(
PETRglobals.AgentDict, text_children[
index:], 0) # checking for agents
if match:
# -- print('NPgm-2.0:',roots)
codes += match[0]
roots += [['~']]
index += match[2]
matched_txt += [match[1]]
# print('agents:')
# print(text_children)
"""print('NPgm-2:',matched_txt) # --
print('NPgm-2.1:',roots)"""
continue
index += 1
"""print('NPgm-m-codes:',codes)
print('NPgm-m-roots:',roots)"""
# combine the actor/agent codes
actorcodes, agentcodes = self.resolve_codes(codes)
txtstrg = self.get_text()[0]
"""print('NPgm-m-actorcodes:',actorcodes)
print('NPgm-m-roots :',roots)
print('NPgm-m-text :',txtstrg, len(txtstrg.split()))"""
if not actorcodes and PETRglobals.NullActors:
if PETRglobals.NewActorLength and len(
txtstrg.split()) < PETRglobals.NewActorLength:
actorcodes = ['*' + str(self.sentence.actoridx) + '*']
self.sentence.actoridx += 1
matched_txt += [txtstrg]
PPactor, PPagent = self.resolve_codes(PPcodes)
NPactor, NPagent = self.resolve_codes(NPcodes)
VPactor, VPagent = self.resolve_codes(VPcodes)
if not actorcodes:
actorcodes += NPactor # don't really need += here, right? pas 16.04.26
if not actorcodes:
actorcodes += PPactor
if not actorcodes:
# CN: Do we want to pull meanings from verb phrases? Could
# be risky
actorcodes += VPactor
if not agentcodes:
agentcodes += NPagent
if not agentcodes:
agentcodes += PPagent
if not agentcodes:
agentcodes += VPagent
"""if len(actorcodes) > 0:
print('NPgm-m-actorcodes:',actorcodes)
print('NPgm-m-roots :',roots)"""
self.meaning = self.mix_codes(agentcodes, actorcodes)
self.get_meaning = self.return_meaning
"""print('NPgm-3:',self.meaning)
print('NPgm-4:',matched_txt)"""
if matched_txt:
self.sentence.metadata[
'nouns'] += [(matched_txt, self.meaning, roots[:len(matched_txt)])]
# self.sentence.print_nouns('NPgm-5:') # --
return self.meaning
def convert_existential(self):
# Reshuffle the tree to get existential "There are" phrases into a more
# basic form
parent = self.parent
sister = parent.children[1]
neice = sister.children[1]
subject = neice.children[0]
predicate = neice.children[1]
parent.children[0] = subject
subject.parent = parent
sister.children[1] = predicate
predicate.parent = sister
self.parent = None
# parent.print_to_stdout("")
return subject
class PrepPhrase(Phrase):
def __init__(self, label, date, sentence):
Phrase.__init__(self, label, date, sentence)
self.meaning = ""
self.prep = ""
self.head = ""
def get_meaning(self):
"""
Return the meaning of the non-preposition constituent, and store the
preposition.
"""
self.prep = self.children[0].text
if len(self.children) > 1 and not self.children[1].color:
self.meaning = self.children[1].get_meaning() if isinstance(
self.children[1], NounPhrase) else ""
# -- print('PPgm-2',self.meaning) # --
self.head = self.children[1].get_head()[0]
return self.meaning
def get_prep(self):
return self.children[0].text
class VerbPhrase(Phrase):
"""
Subclass specific to Verb Phrases
Methods
-------
__init__: Initialization and Instatiation
is_valid: Corrects a known stanford error regarding miscoded noun phrases
get_theme: Returns the coded target of the VP
get_meaning: Returns event coding described by the verb phrase
get_lower: Finds meanings of children
get_upper: Finds grammatical subject
get_code: Finds base verb code and calls match_pattern
match_pattern: Matches the tree to a pattern in the Verb Dictionary
get_S: Finds the closest S-level phrase above the verb
match_transform: Matches an event code against transformation patterns in the dictionary
"""
def __init__(self, label, date, sentence):
Phrase.__init__(self, label, date, sentence)
self.meaning = "" # "meaning" for the verb, i.e. the events coded by the vp
# contains the meaning of the noun phrase in the specifier position for
# the vp or its parents
self.upper = ""
self.lower = "" # contains the meaning of the subtree c-commanded by the verb
self.passive = False
self.code = 0
self.valid = self.is_valid()
self.S = None
def is_valid(self):
"""
This method is largely to overcome frequently made Stanford errors, where phrases like "exiled dissidents" were
marked as verb phrases, and treating them as such would yield weird parses.
Once such a phrase is identified because of its weird distribution, it is converted to
a NounPhrase object
"""
try:
if self.children[0].label == "VBN":
helping = ["HAVE", "HAD", "HAVING", "HAS"]
if ((not (self.parent.get_head()[0] in helping or self.parent.children[0].text in helping)) and
len(filter(lambda a: isinstance(a, VerbPhrase), self.parent.children)) <= 1 and
not self.check_passive()):
self.valid = False
np_replacement = NounPhrase("NP", self.date, self.sentence)
np_replacement.children = self.children
np_replacement.parent = self.parent
np_replacement.index = self.index
self.parent.children.remove(self)
self.parent.children.insert(self.index, np_replacement)
del(self)
self = np_replacement
return False
self.valid = True
except IndexError as e:
self.valid = True
return True
def get_theme(self):
"""
This is used by the NounPhrase.get_meaning() method to determine relevant
information in the VerbPhrase.
"""
m = self.get_meaning()
if isinstance(m[0], basestring):
return [m[0]]
if m[0][1] == 'passive':
return m[0][0]
return [m[0][1]]
def return_meaning(self):
return self.meaning
def get_meaning(self):
"""
This determines the event coding of the subtree rooted in this verb phrase.
Four methods are key in this process: get_upper(), get_lower(), get_code()
and match_transform().
First, get_meaning() gets the verb code from get_code()
Then, it checks passivity. If the verb is passive, then it looks within
verb phrases headed by [by, from, in] for the source, and for an explicit target
in verb phrases headed by [at,against,into,towards]. If no target is found,
this space is filled with 'passive', a flag used later to assign a target
if it is in the grammatical subject position.
If the verb is not passive, then the process goes:
1) call get_upper() and get_lower() to check for a grammatical subject
and find the coding of the subtree and children, respectively.
2) If get_lower returned a list of events, combine those events with
the upper and code, add to event list.
3) Otherwise, combine upper, lower, and code and add to event list
4) Check to see if there are S-level children, if so, combine with
upper and code, add to list.
5) call match_transform() on all events in the list
Parameters
----------
self: VerbPhrase object that called the method
Returns
-------
events: list
List of events coded by the subtree rooted in this phrase.
"""
time1 = time.time()
self.get_meaning = self.return_meaning
c, passive, meta = self.get_code()
"""print('VP-gm-0:',self.get_text())
print('VP-gm-1:',c, meta)"""
if c:
curparse = '==CODED=='
else:
curparse = self.get_parse_string()
s_options = filter(lambda a: a.label in "SBAR", self.children)
def resolve_events(event):
"""
Helper method to combine events, accounting for
missing sources, and targets, passives, multiple-
target passives, and codeless verbs.
Parameters
----------
event: tuple
(source, target, code) of lower event
Returns
-------
returns: [tuple]
list of resolved event tuples
"""
returns = []
first, second, third = [up, "", ""]
if not (up or c):
return [event]
if not isinstance(event, tuple):
second = event
third = c
if passive:
for item in first:
e2 = ([second], item, passive)
self.sentence.metadata[id(e2)] = [event, meta, 7]
returns.append(e2)
elif event[1] == 'passive':
first = event[0]
third = utilities.combine_code(c, event[2])
if up:
returns = []
for source in up:
e = (first, source, third)
self.sentence.metadata[id(e)] = [event, up, 1]
returns.append(e)
return returns
second = 'passive'
elif not event[0] in ['', [], [""], ["~"], ["~~"]]:
second = event
third = c
else:
second = event[1]
third = utilities.combine_code(c, event[2])
e = (first, second, third)
self.sentence.metadata[id(e)] = [event, c, meta, 2]
return returns + [e]
events = []
up = self.get_upper()
if self.check_passive() or (passive and not c):
# Check for source in preps
source_options = []
target_options = up
for child in self.children:
if isinstance(child, PrepPhrase):
if child.get_prep() in ["BY", "FROM", "IN"]:
source_options += child.get_meaning()
meta.append((child.prep, child.get_meaning()))
elif child.get_prep() in ["AT", "AGAINST", "INTO", "TOWARDS"]:
target_options += child.get_meaning()
meta.append((child.prep, child.get_meaning()))
if not target_options:
target_options = ["passive"]
if source_options or c:
for i in target_options:
e = (
source_options,
i,
c if self.check_passive() else passive)
events.append(e)
self.sentence.metadata[id(e)] = [None, e, meta, 3]
self.meaning = events
return events
up = "" if up in ['', [], [""], ["~"], ["~~"]] else up
low, neg = self.get_lower()
if not low:
low = ""
if neg:
c = 0
if isinstance(low, list):
for event in low:
events += resolve_events(event)
elif not s_options:
if up or c:
e = (up, low, c)
self.sentence.metadata[id(e)] = [None, e, 4]
events.append(e)
elif low:
events.append(low)
lower = map(lambda a: a.get_meaning(), s_options)
sents = []
for item in lower:
sents += item
if sents and not events: # Only if nothing else has been found do we look at lower NP's?
# This decreases our coding frequency, but
# removes many false positives
for event in sents:
if isinstance(event, tuple) and (event[1] or event[2]):
for ev in resolve_events(event):
if isinstance(ev[1], list):
for item in ev[1]:
local = (ev[0], item, ev[2])
self.sentence.metadata[id(local)] = [
ev, item, 5]
events.append(local)
else:
events += resolve_events(event)
# -- print('@@-1',events)
if events and isinstance(events[0], tuple):
# -- print('@@-2',events[0])
if events[0][0] and events[0][1] and not events[0][2]:
utilities.nulllist.append((curparse, events[0]))
# -- print('@@-3',utilities.nulllist)
maps = []
for i in events:
evs = self.match_transform(i)
if isinstance(evs, tuple):
for j in evs[0]:
maps.append(j)
self.sentence.metadata[id(j)] = [i, evs[1], 6]
else:
maps += evs
self.meaning = maps
return maps
def return_upper(self):
return self.upper
def return_passive(self):
return self.passive
def check_passive(self):
"""
Check if the verb is passive under these conditions:
1) Verb is -ed form, which is notated by stanford as VBD or VBN
2) Verb has a form of "be" as its next highest verb
Parameters
----------
self: VerbPhrase object calling the method
Returns
-------
self.passive: boolean
Whether or not it is passive
"""
# -- print('cp-entry')
self.check_passive = self.return_passive
if True:
if self.children[0].label in ["VBD", "VBN"]:
level = self.parent
if level.label == "NP":
self.passive = True
return True
for i in range(2):
if level and isinstance(level, VerbPhrase):
if level.children[0].text in [
"AM", "IS", "ARE",
"WAS", "WERE", "BE", "BEEN", "BEING"]:
self.passive = True
return True
level = level.parent
if not level:
break
else:
print("Error in passive check")
self.passive = False
return False
def return_S(self):
# -- print('rS-entry')
return self.S
def get_S(self):
"""