-
Notifications
You must be signed in to change notification settings - Fork 22
/
tree.py
executable file
·1851 lines (1588 loc) · 71.3 KB
/
tree.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
#### PATTERN | EN | PARSE TREE #####################################################################
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <[email protected]>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
####################################################################################################
# Text and Sentence objects to traverse words and chunks in parsed text.
# from pattern.en import parsetree
# for sentence in parsetree("The cat sat on the mat."):
# for chunk in sentence.chunks:
# for word in chunk.words:
# print(word.string, word.tag, word.lemma)
# Terminology:
# - part-of-speech: the role that a word plays in a sentence: noun (NN), verb (VB), adjective, ...
# - sentence: a unit of language, with a subject (e.g., "the cat") and a predicate ("jumped").
# - token: a word in a sentence with a part-of-speech tag (e.g., "jump/VB" or "jump/NN").
# - word: a string of characters that expresses a meaningful concept (e.g., "cat").
# - lemma: the canonical word form ("jumped" => "jump").
# - lexeme: the set of word forms ("jump", "jumps", "jumping", ...)
# - chunk: a phrase, group of words that express a single thought (e.g., "the cat").
# - subject: the phrase that the sentence is about, usually a noun phrase.
# - predicate: the remainder of the sentence tells us what the subject does (jump).
# - object: the phrase that is affected by the action (the cat jumped [the mouse]").
# - preposition: temporal, spatial or logical relationship ("the cat jumped [on the table]").
# - anchor: the chunk to which the preposition is attached:
# "the cat eats its snackerel with vigor" => eat with vigor?
# OR => vigorous snackerel?
# The Text and Sentece classes are containers:
# no parsing functionality should be added to it.
from __future__ import unicode_literals
from __future__ import division
from builtins import str, bytes, dict, int
from builtins import map, zip, filter
from builtins import object, range
from io import open
from itertools import chain
try:
from config import SLASH
from config import WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA
MBSP = True # Memory-Based Shallow Parser for Python.
except:
SLASH, WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA = \
"&slash;", "word", "part-of-speech", "chunk", "preposition", "relation", "anchor", "lemma"
MBSP = False
# B- marks the start of a chunk: the/DT/B-NP cat/NN/I-NP
# I- words are inside a chunk.
# O- words are outside a chunk (punctuation etc.).
IOB, BEGIN, INSIDE, OUTSIDE = "IOB", "B", "I", "O"
# -SBJ marks subjects: the/DT/B-NP-SBJ cat/NN/I-NP-SBJ
# -OBJ marks objects.
ROLE = "role"
SLASH0 = SLASH[0]
### LIST FUNCTIONS #################################################################################
def find(function, iterable):
""" Returns the first item in the list for which function(item) is True, None otherwise.
"""
for x in iterable:
if function(x):
return x
def intersects(iterable1, iterable2):
""" Returns True if the given lists have at least one item in common.
"""
return find(lambda x: x in iterable1, iterable2) is not None
def unique(iterable):
""" Returns a list copy in which each item occurs only once (in-order).
"""
seen = set()
return [x for x in iterable if x not in seen and not seen.add(x)]
_zip = zip
def zip(*args, **kwargs):
""" Returns a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables (or default if too short).
"""
args = [list(iterable) for iterable in args]
n = max(map(len, args))
v = kwargs.get("default", None)
return list(_zip(*[i + [v] * (n - len(i)) for i in args]))
def unzip(i, iterable):
""" Returns the item at the given index from inside each tuple in the list.
"""
return [x[i] for x in iterable]
class Map(list):
""" A stored imap() on a list.
The list is referenced instead of copied, and the items are mapped on-the-fly.
"""
def __init__(self, function=lambda x: x, items=[]):
self._f = function
self._a = items
@property
def items(self):
return self._a
def __repr__(self):
return repr(list(iter(self)))
def __getitem__(self, i):
return self._f(self._a[i])
def __len__(self):
return len(self._a)
def __iter__(self):
i = 0
while i < len(self._a):
yield self._f(self._a[i])
i += 1
### SENTENCE #######################################################################################
# The output of parse() is a slash-formatted string (e.g., "the/DT cat/NN"),
# so slashes in words themselves are encoded as &slash;
encode_entities = lambda string: string.replace("/", SLASH)
decode_entities = lambda string: string.replace(SLASH, "/")
#--- WORD ------------------------------------------------------------------------------------------
class Word(object):
def __init__(self, sentence, string, lemma=None, type=None, index=0):
""" A word in the sentence.
- lemma: base form of the word; "was" => "be".
- type: the part-of-speech tag; "NN" => a noun.
- chunk: the chunk (or phrase) this word belongs to.
- index: the index in the sentence.
"""
if not isinstance(string, str):
try:
string = string.decode("utf-8") # ensure Unicode
except:
pass
self.sentence = sentence
self.index = index
self.string = string # "was"
self.lemma = lemma # "be"
self.type = type # VB
self.chunk = None # Chunk object this word belongs to (i.e., a VP).
self.pnp = None # PNP chunk object this word belongs to.
# word.chunk and word.pnp are set in chunk.append().
self._custom_tags = None # Tags object, created on request.
def copy(self, chunk=None, pnp=None):
w = Word(
self.sentence,
self.string,
self.lemma,
self.type,
self.index
)
w.chunk = chunk
w.pnp = pnp
if self._custom_tags:
w._custom_tags = Tags(w, items=self._custom_tags)
return w
def _get_tag(self):
return self.type
def _set_tag(self, v):
self.type = v
tag = pos = part_of_speech = property(_get_tag, _set_tag)
@property
def phrase(self):
return self.chunk
@property
def prepositional_phrase(self):
return self.pnp
prepositional_noun_phrase = prepositional_phrase
@property
def tags(self):
""" Yields a list of all the token tags as they appeared when the word was parsed.
For example: ["was", "VBD", "B-VP", "O", "VP-1", "A1", "be"]
"""
# See also. Sentence.__repr__().
ch, I, O, B = self.chunk, INSIDE + "-", OUTSIDE, BEGIN + "-"
tags = [OUTSIDE for i in range(len(self.sentence.token))]
for i, tag in enumerate(self.sentence.token): # Default: [WORD, POS, CHUNK, PNP, RELATION, ANCHOR, LEMMA]
if tag == WORD:
tags[i] = encode_entities(self.string)
elif tag == POS or tag == "pos" and self.type:
tags[i] = self.type
elif tag == CHUNK and ch and ch.type:
tags[i] = (self == ch[0] and B or I) + ch.type
elif tag == PNP and self.pnp:
tags[i] = (self == self.pnp[0] and B or I) + "PNP"
elif tag == REL and ch and len(ch.relations) > 0:
tags[i] = ["-".join([str(x) for x in [ch.type] + list(reversed(r)) if x]) for r in ch.relations]
tags[i] = "*".join(tags[i])
elif tag == ANCHOR and ch:
tags[i] = ch.anchor_id or OUTSIDE
elif tag == LEMMA:
tags[i] = encode_entities(self.lemma or "")
elif tag in self.custom_tags:
tags[i] = self.custom_tags.get(tag) or OUTSIDE
return tags
@property
def custom_tags(self):
if not self._custom_tags:
self._custom_tags = Tags(self)
return self._custom_tags
def next(self, type=None):
""" Returns the next word in the sentence with the given type.
"""
i = self.index + 1
s = self.sentence
while i < len(s):
if type in (s[i].type, None):
return s[i]
i += 1
def previous(self, type=None):
""" Returns the next previous word in the sentence with the given type.
"""
i = self.index - 1
s = self.sentence
while i > 0:
if type in (s[i].type, None):
return s[i]
i -= 1
# User-defined tags are available as Word.[tag] attributes.
def __getattr__(self, tag):
d = self.__dict__.get("_custom_tags", None)
if d and tag in d:
return d[tag]
raise AttributeError("Word instance has no attribute '%s'" % tag)
# Word.string and unicode(Word) are Unicode strings.
# repr(Word) is a Python string (with Unicode characters encoded).
def __str__(self):
return self.string
def __repr__(self):
return "Word(%s)" % repr("%s/%s" % (
encode_entities(self.string),
self.type is not None and self.type or OUTSIDE))
def __eq__(self, word):
return id(self) == id(word)
def __ne__(self, word):
return id(self) != id(word)
# This is required because we overwrite the parent's __eq__() method.
# Otherwise objects will be unhashable in Python 3.
# More information: http://docs.python.org/3.6/reference/datamodel.html#object.__hash__
__hash__ = object.__hash__
class Tags(dict):
def __init__(self, word, items=[]):
""" A dictionary of custom word tags.
A word may be annotated with its part-of-speech tag (e.g., "cat/NN"),
phrase tag (e.g., "cat/NN/NP"), the prepositional noun phrase it is part of etc.
An example of an extra custom slot is its semantic type,
e.g., gene type, topic, and so on: "cat/NN/NP/genus_felis"
"""
if items:
dict.__init__(self, items)
self.word = word
def __setitem__(self, k, v):
# Ensure that the custom tag is also in Word.sentence.token,
# so that it is not forgotten when exporting or importing XML.
dict.__setitem__(self, k, v)
if k not in reversed(self.word.sentence.token):
self.word.sentence.token.append(k)
def setdefault(self, k, v):
if k not in self:
self.__setitem__(k, v)
return self[k]
#--- CHUNK -----------------------------------------------------------------------------------------
class Chunk(object):
def __init__(self, sentence, words=[], type=None, role=None, relation=None):
""" A list of words that make up a phrase in the sentence.
- type: the phrase tag; "NP" => a noun phrase (e.g., "the black cat").
- role: the function of the phrase; "SBJ" => sentence subject.
- relation: an id shared with other phrases, linking subject to object in the sentence.
"""
# A chunk can have multiple roles or relations in the sentence,
# so role and relation can also be given as lists.
b1 = isinstance(relation, (list, tuple))
b2 = isinstance(role, (list, tuple))
if not b1 and not b2:
r = [(relation, role)]
elif b1 and b2:
r = list(zip(relation, role))
elif b1:
r = list(zip(relation, [role] * len(relation)))
elif b2:
r = list(zip([relation] * len(role), role))
r = [(a, b) for a, b in r if a is not None or b is not None]
self.sentence = sentence
self.words = []
self.type = type # NP, VP, ADJP ...
self.relations = r # NP-SBJ-1 => [(1, SBJ)]
self.pnp = None # PNP chunk object this chunk belongs to.
self.anchor = None # PNP chunk's anchor.
self.attachments = [] # PNP chunks attached to this anchor.
self._conjunctions = None # Conjunctions object, created on request.
self._modifiers = None
self.extend(words)
def extend(self, words):
for w in words:
self.append(w)
def append(self, word):
self.words.append(word)
word.chunk = self
def __getitem__(self, index):
return self.words[index]
def __len__(self):
return len(self.words)
def __iter__(self):
return self.words.__iter__()
def _get_tag(self):
return self.type
def _set_tag(self, v):
self.type = v
tag = pos = part_of_speech = property(_get_tag, _set_tag)
@property
def start(self):
return self.words[0].index
@property
def stop(self):
return self.words[-1].index + 1
@property
def range(self):
return range(self.start, self.stop)
@property
def span(self):
return (self.start, self.stop)
@property
def lemmata(self):
return [word.lemma for word in self.words]
@property
def tagged(self):
return [(word.string, word.type) for word in self.words]
@property
def head(self):
""" Yields the head of the chunk (usually, the last word in the chunk).
"""
if self.type == "NP" and any(w.type.startswith("NNP") for w in self):
w = find(lambda w: w.type.startswith("NNP"), reversed(self))
elif self.type == "NP": # "the cat" => "cat"
w = find(lambda w: w.type.startswith("NN"), reversed(self))
elif self.type == "VP": # "is watching" => "watching"
w = find(lambda w: w.type.startswith("VB"), reversed(self))
elif self.type == "PP": # "from up on" => "from"
w = find(lambda w: w.type.startswith(("IN", "PP")), self)
elif self.type == "PNP": # "from up on the roof" => "roof"
w = find(lambda w: w.type.startswith("NN"), reversed(self))
else:
w = None
if w is None:
w = self[-1]
return w
@property
def relation(self):
""" Yields the first relation id of the chunk.
"""
# [(2,OBJ), (3,OBJ)])] => 2
return len(self.relations) > 0 and self.relations[0][0] or None
@property
def role(self):
""" Yields the first role of the chunk (SBJ, OBJ, ...).
"""
# [(1,SBJ), (1,OBJ)])] => SBJ
return len(self.relations) > 0 and self.relations[0][1] or None
@property
def subject(self):
ch = self.sentence.relations["SBJ"].get(self.relation, None)
if ch != self:
return ch
@property
def object(self):
ch = self.sentence.relations["OBJ"].get(self.relation, None)
if ch != self:
return ch
@property
def verb(self):
ch = self.sentence.relations["VP"].get(self.relation, None)
if ch != self:
return ch
@property
def related(self):
""" Yields a list of all chunks in the sentence with the same relation id.
"""
return [ch for ch in self.sentence.chunks
if ch != self and intersects(unzip(0, ch.relations), unzip(0, self.relations))]
@property
def prepositional_phrase(self):
return self.pnp
prepositional_noun_phrase = prepositional_phrase
@property
def anchor_id(self):
""" Yields the anchor tag as parsed from the original token.
Chunks that are anchors have a tag with an "A" prefix (e.g., "A1").
Chunks that are PNP attachmens (or chunks inside a PNP) have "P" (e.g., "P1").
Chunks inside a PNP can be both anchor and attachment (e.g., "P1-A2"),
as in: "clawed/A1 at/P1 mice/P1-A2 in/P2 the/P2 wall/P2"
"""
id = ""
f = lambda ch: list(filter(lambda k: self.sentence._anchors[k] == ch, self.sentence._anchors))
if self.pnp and self.pnp.anchor:
id += "-" + "-".join(f(self.pnp))
if self.anchor:
id += "-" + "-".join(f(self))
if self.attachments:
id += "-" + "-".join(f(self))
return id.strip("-") or None
@property
def conjunctions(self):
if not self._conjunctions:
self._conjunctions = Conjunctions(self)
return self._conjunctions
@property
def modifiers(self):
""" For verb phrases (VP), yields a list of the nearest adjectives and adverbs.
"""
if self._modifiers is None:
# Iterate over all the chunks and attach modifiers to their VP-anchor.
is_modifier = lambda ch: ch.type in ("ADJP", "ADVP") and ch.relation is None
for chunk in self.sentence.chunks:
chunk._modifiers = []
for chunk in filter(is_modifier, self.sentence.chunks):
anchor = chunk.nearest("VP")
if anchor:
anchor._modifiers.append(chunk)
return self._modifiers
def nearest(self, type="VP"):
""" Returns the nearest chunk in the sentence with the given type.
This can be used (for example) to find adverbs and adjectives related to verbs,
as in: "the cat is ravenous" => is what? => "ravenous".
"""
candidate, d = None, len(self.sentence.chunks)
if isinstance(self, PNPChunk):
i = self.sentence.chunks.index(self.chunks[0])
else:
i = self.sentence.chunks.index(self)
for j, chunk in enumerate(self.sentence.chunks):
if chunk.type.startswith(type) and abs(i - j) < d:
candidate, d = chunk, abs(i - j)
return candidate
def next(self, type=None):
""" Returns the next chunk in the sentence with the given type.
"""
i = self.stop
s = self.sentence
while i < len(s):
if s[i].chunk is not None and type in (s[i].chunk.type, None):
return s[i].chunk
i += 1
def previous(self, type=None):
""" Returns the next previous chunk in the sentence with the given type.
"""
i = self.start - 1
s = self.sentence
while i > 0:
if s[i].chunk is not None and type in (s[i].chunk.type, None):
return s[i].chunk
i -= 1
# Chunk.string and unicode(Chunk) are Unicode strings.
# repr(Chunk) is a Python string (with Unicode characters encoded).
@property
def string(self):
return " ".join(word.string for word in self.words)
def __str__(self):
return self.string
def __repr__(self):
return "Chunk(%s)" % repr("%s/%s%s%s") % (
self.string,
self.type is not None and self.type or OUTSIDE,
self.role is not None and ("-" + self.role) or "",
self.relation is not None and ("-" + str(self.relation)) or "")
def __eq__(self, chunk):
return id(self) == id(chunk)
def __ne__(self, chunk):
return id(self) != id(chunk)
# This is required because we overwrite the parent's __eq__() method.
# Otherwise objects will be unhashable in Python 3.
# More information: http://docs.python.org/3.6/reference/datamodel.html#object.__hash__
__hash__ = object.__hash__
# Chinks are non-chunks,
# see also the chunked() function:
class Chink(Chunk):
def __repr__(self):
return Chunk.__repr__(self).replace("Chunk(", "Chink(", 1)
#--- PNP CHUNK -------------------------------------------------------------------------------------
class PNPChunk(Chunk):
def __init__(self, *args, **kwargs):
""" A chunk of chunks that make up a prepositional noun phrase (i.e., PP + NP).
When the output of the parser includes PP-attachment,
PNPChunck.anchor will yield the chunk that is clarified by the preposition.
For example: "the cat went [for the mouse] [with its claws]":
- [went] what? => for the mouse,
- [went] how? => with its claws.
"""
self.anchor = None # The anchor chunk (e.g., "for the mouse" => "went").
self.chunks = [] # List of chunks in the prepositional noun phrase.
Chunk.__init__(self, *args, **kwargs)
def append(self, word):
self.words.append(word)
word.pnp = self
if word.chunk is not None:
word.chunk.pnp = self
if word.chunk not in self.chunks:
self.chunks.append(word.chunk)
@property
def preposition(self):
""" Yields the first chunk in the prepositional noun phrase, usually a PP-chunk.
PP-chunks contain words such as "for", "with", "in", ...
"""
return self.chunks[0]
pp = preposition
@property
def phrases(self):
return self.chunks
def guess_anchor(self):
""" Returns an anchor chunk for this prepositional noun phrase (without a PP-attacher).
Often, the nearest verb phrase is a good candidate.
"""
return self.nearest("VP")
#--- CONJUNCTION -----------------------------------------------------------------------------------
CONJUNCT = AND = "AND"
DISJUNCT = OR = "OR"
class Conjunctions(list):
def __init__(self, chunk):
""" Chunk.conjunctions is a list of other chunks participating in a conjunction.
Each item in the list is a (chunk, conjunction)-tuple, with conjunction either AND or OR.
"""
self.anchor = chunk
def append(self, chunk, type=CONJUNCT):
list.append(self, (chunk, type))
#--- SENTENCE --------------------------------------------------------------------------------------
_UID = 0
def _uid():
global _UID
_UID += 1
return _UID
def _is_tokenstring(string):
# The class mbsp.TokenString stores the format of tags for each token.
# Since it comes directly from MBSP.parse(), this format is always correct,
# regardless of the given token format parameter for Sentence() or Text().
return isinstance(string, str) and hasattr(string, "tags")
class Sentence(object):
def __init__(self, string="", token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA], language="en"):
""" A nested tree of sentence words, chunks and prepositions.
The input is a tagged string from parse().
The order in which token tags appear can be specified.
"""
# Extract token format from TokenString or TaggedString if possible.
if _is_tokenstring(string):
token, language = string.tags, getattr(string, "language", language)
# Convert to Unicode.
if not isinstance(string, str):
for encoding in (("utf-8",), ("windows-1252",), ("utf-8", "ignore")):
try:
string = string.decode(*encoding)
except:
pass
self.parent = None # A Slice refers to the Sentence it is part of.
self.text = None # A Sentence refers to the Text it is part of.
self.language = language
self.id = _uid()
self.token = list(token)
self.words = []
self.chunks = [] # Words grouped into chunks.
self.pnp = [] # Words grouped into PNP chunks.
self._anchors = {} # Anchor tags related to anchor chunks or attached PNP's.
self._relation = None # Helper variable: the last chunk's relation and role.
self._attachment = None # Helper variable: the last attachment tag (e.g., "P1") parsed in _do_pnp().
self._previous = None # Helper variable: the last token parsed in parse_token().
self.relations = {"SBJ": {}, "OBJ": {}, "VP": {}}
# Split the slash-formatted token into the separate tags in the given order.
# Append Word and Chunk objects according to the token's tags.
for chars in string.split(" "):
if chars:
self.append(*self.parse_token(chars, token))
@property
def word(self):
return self.words
@property
def lemmata(self):
return Map(lambda w: w.lemma, self.words)
#return [word.lemma for word in self.words]
lemma = lemmata
@property
def parts_of_speech(self):
return Map(lambda w: w.type, self.words)
#return [word.type for word in self.words]
pos = parts_of_speech
@property
def tagged(self):
return [(word.string, word.type) for word in self]
@property
def phrases(self):
return self.chunks
chunk = phrases
@property
def prepositional_phrases(self):
return self.pnp
prepositional_noun_phrases = prepositional_phrases
@property
def start(self):
return 0
@property
def stop(self):
return self.start + len(self.words)
@property
def nouns(self):
return [word for word in self if word.type.startswith("NN")]
@property
def verbs(self):
return [word for word in self if word.type.startswith("VB")]
@property
def adjectives(self):
return [word for word in self if word.type.startswith("JJ")]
@property
def subjects(self):
return list(self.relations["SBJ"].values())
@property
def objects(self):
return list(self.relations["OBJ"].values())
@property
def verbs(self):
return list(self.relations["VP"].values())
@property
def anchors(self):
return [chunk for chunk in self.chunks if len(chunk.attachments) > 0]
@property
def is_question(self):
return len(self) > 0 and str(self[-1]) == "?"
@property
def is_exclamation(self):
return len(self) > 0 and str(self[-1]) == "!"
def __getitem__(self, index):
return self.words[index]
def __len__(self):
return len(self.words)
def __iter__(self):
return self.words.__iter__()
def append(self, word, lemma=None, type=None, chunk=None, role=None, relation=None, pnp=None, anchor=None, iob=None, custom={}):
""" Appends the next word to the sentence / chunk / preposition.
For example: Sentence.append("clawed", "claw", "VB", "VP", role=None, relation=1)
- word : the current word,
- lemma : the canonical form of the word,
- type : part-of-speech tag for the word (NN, JJ, ...),
- chunk : part-of-speech tag for the chunk this word is part of (NP, VP, ...),
- role : the chunk's grammatical role (SBJ, OBJ, ...),
- relation : an id shared by other related chunks (e.g., SBJ-1 <=> VP-1),
- pnp : PNP if this word is in a prepositional noun phrase (B- prefix optional),
- iob : BEGIN if the word marks the start of a new chunk,
INSIDE (optional) if the word is part of the previous chunk,
- custom : a dictionary of (tag, value)-items for user-defined word tags.
"""
self._do_word(word, lemma, type) # Append Word object.
self._do_chunk(chunk, role, relation, iob) # Append Chunk, or add last word to last chunk.
self._do_conjunction()
self._do_relation()
self._do_pnp(pnp, anchor)
self._do_anchor(anchor)
self._do_custom(custom)
def parse_token(self, token, tags=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
""" Returns the arguments for Sentence.append() from a tagged token representation.
The order in which token tags appear can be specified.
The default order is (separated by slashes):
- word,
- part-of-speech,
- (IOB-)chunk,
- (IOB-)preposition,
- chunk(-relation)(-role),
- anchor,
- lemma.
Examples:
The/DT/B-NP/O/NP-SBJ-1/O/the
cats/NNS/I-NP/O/NP-SBJ-1/O/cat
clawed/VBD/B-VP/O/VP-1/A1/claw
at/IN/B-PP/B-PNP/PP/P1/at
the/DT/B-NP/I-PNP/NP/P1/the
sofa/NN/I-NP/I-PNP/NP/P1/sofa
././O/O/O/O/.
Returns a (word, lemma, type, chunk, role, relation, preposition, anchor, iob, custom)-tuple,
which can be passed to Sentence.append(): Sentence.append(*Sentence.parse_token("cats/NNS/NP"))
The custom value is a dictionary of (tag, value)-items of unrecognized tags in the token.
"""
p = {WORD: "",
POS: None,
IOB: None,
CHUNK: None,
PNP: None,
REL: None,
ROLE: None,
ANCHOR: None,
LEMMA: None}
# Split the slash-formatted token into separate tags in the given order.
# Decode &slash; characters (usually in words and lemmata).
# Assume None for missing tags (except the word itself, which defaults to an empty string).
custom = {}
for k, v in zip(tags, token.split("/")):
if SLASH0 in v:
v = v.replace(SLASH, "/")
if k == "pos":
k = POS
if k not in p:
custom[k] = None
if v != OUTSIDE or k == WORD or k == LEMMA: # "type O negative" => "O" != OUTSIDE.
(p if k not in custom else custom)[k] = v
# Split IOB-prefix from the chunk tag:
# B- marks the start of a new chunk,
# I- marks inside of a chunk.
ch = p[CHUNK]
if ch is not None and ch.startswith(("B-", "I-")):
p[IOB], p[CHUNK] = ch[:1], ch[2:] # B-NP
# Split the role from the relation:
# NP-SBJ-1 => relation id is 1 and role is SBJ,
# VP-1 => relation id is 1 with no role.
# Tokens may be tagged with multiple relations (e.g., NP-OBJ-1*NP-OBJ-3).
if p[REL] is not None:
ch, p[REL], p[ROLE] = self._parse_relation(p[REL])
# Infer a missing chunk tag from the relation tag (e.g., NP-SBJ-1 => NP).
# For PP relation tags (e.g., PP-CLR-1), the first chunk is PP, the following chunks NP.
if ch == "PP" \
and self._previous \
and self._previous[REL] == p[REL] \
and self._previous[ROLE] == p[ROLE]:
ch = "NP"
if p[CHUNK] is None and ch != OUTSIDE:
p[CHUNK] = ch
self._previous = p
# Return the tags in the right order for Sentence.append().
return p[WORD], p[LEMMA], p[POS], p[CHUNK], p[ROLE], p[REL], p[PNP], p[ANCHOR], p[IOB], custom
def _parse_relation(self, tag):
""" Parses the chunk tag, role and relation id from the token relation tag.
- VP => VP, [], []
- VP-1 => VP, [1], [None]
- ADJP-PRD => ADJP, [None], [PRD]
- NP-SBJ-1 => NP, [1], [SBJ]
- NP-OBJ-1*NP-OBJ-2 => NP, [1,2], [OBJ,OBJ]
- NP-SBJ;NP-OBJ-1 => NP, [1,1], [SBJ,OBJ]
"""
chunk, relation, role = None, [], []
if ";" in tag:
# NP-SBJ;NP-OBJ-1 => 1 relates to both SBJ and OBJ.
id = tag.split("*")[0][-2:]
id = id if id.startswith("-") else ""
tag = tag.replace(";", id + "*")
if "*" in tag:
tag = tag.split("*")
else:
tag = [tag]
for s in tag:
s = s.split("-")
n = len(s)
if n == 1:
chunk = s[0]
if n == 2:
chunk = s[0]
relation.append(s[1])
role.append(None)
if n >= 3:
chunk = s[0]
relation.append(s[2])
role.append(s[1])
if n > 1:
id = relation[-1]
if id.isdigit():
relation[-1] = int(id)
else:
# Correct "ADJP-PRD":
# (ADJP, [PRD], [None]) => (ADJP, [None], [PRD])
relation[-1], role[-1] = None, id
return chunk, relation, role
def _do_word(self, word, lemma=None, type=None):
""" Adds a new Word to the sentence.
Other Sentence._do_[tag] functions assume a new word has just been appended.
"""
# Improve 3rd person singular "'s" lemma to "be", e.g., as in "he's fine".
if lemma == "'s" and type in ("VB", "VBZ"):
lemma = "be"
self.words.append(Word(self, word, lemma, type, index=len(self.words)))
def _do_chunk(self, type, role=None, relation=None, iob=None):
""" Adds a new Chunk to the sentence, or adds the last word to the previous chunk.
The word is attached to the previous chunk if both type and relation match,
and if the word's chunk tag does not start with "B-" (i.e., iob != BEGIN).
Punctuation marks (or other "O" chunk tags) are not chunked.
"""
if (type is None or type == OUTSIDE) and \
(role is None or role == OUTSIDE) and (relation is None or relation == OUTSIDE):
return
if iob != BEGIN \
and self.chunks \
and self.chunks[-1].type == type \
and self._relation == (relation, role) \
and self.words[-2].chunk is not None: # "one, two" => "one" & "two" different chunks.
self.chunks[-1].append(self.words[-1])
else:
ch = Chunk(self, [self.words[-1]], type, role, relation)
self.chunks.append(ch)
self._relation = (relation, role)
def _do_relation(self):
""" Attaches subjects, objects and verbs.
If the previous chunk is a subject/object/verb, it is stored in Sentence.relations{}.
"""
if self.chunks:
ch = self.chunks[-1]
for relation, role in ch.relations:
if role == "SBJ" or role == "OBJ":
self.relations[role][relation] = ch
if ch.type in ("VP",):
self.relations[ch.type][ch.relation] = ch
def _do_pnp(self, pnp, anchor=None):
""" Attaches prepositional noun phrases.
Identifies PNP's from either the PNP tag or the P-attachment tag.
This does not determine the PP-anchor, it only groups words in a PNP chunk.
"""
if anchor or pnp and pnp.endswith("PNP"):
if anchor is not None:
m = find(lambda x: x.startswith("P"), anchor)
else:
m = None
if self.pnp \
and pnp \
and pnp != OUTSIDE \
and pnp.startswith("B-") is False \
and self.words[-2].pnp is not None:
self.pnp[-1].append(self.words[-1])
elif m is not None and m == self._attachment:
self.pnp[-1].append(self.words[-1])
else:
ch = PNPChunk(self, [self.words[-1]], type="PNP")
self.pnp.append(ch)
self._attachment = m
def _do_anchor(self, anchor):
""" Collects preposition anchors and attachments in a dictionary.
Once the dictionary has an entry for both the anchor and the attachment, they are linked.
"""
if anchor:
for x in anchor.split("-"):
A, P = None, None
if x.startswith("A") and len(self.chunks) > 0: # anchor
A, P = x, x.replace("A", "P")
self._anchors[A] = self.chunks[-1]
if x.startswith("P") and len(self.pnp) > 0: # attachment (PNP)
A, P = x.replace("P", "A"), x
self._anchors[P] = self.pnp[-1]
if A in self._anchors and P in self._anchors and not self._anchors[P].anchor:
pnp = self._anchors[P]
pnp.anchor = self._anchors[A]
pnp.anchor.attachments.append(pnp)
def _do_custom(self, custom):
""" Adds the user-defined tags to the last word.
Custom tags can be used to add extra semantical meaning or metadata to words.
"""
if custom:
self.words[-1].custom_tags.update(custom)
def _do_conjunction(self, _and=("and", "e", "en", "et", "und", "y")):
""" Attach conjunctions.
CC-words like "and" and "or" between two chunks indicate a conjunction.
"""
w = self.words
if len(w) > 2 and w[-2].type == "CC" and w[-2].chunk is None:
cc = w[-2].string.lower() in _and and AND or OR
ch1 = w[-3].chunk