-
Notifications
You must be signed in to change notification settings - Fork 20
/
tree.py
1544 lines (1392 loc) · 66.6 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
#### MEMORY BASED SHALLOW PARSER ######################################################################
# Copyright (c) 2003-2010 University of Antwerp, Belgium and Tilburg University, The Netherlands
# Vincent Van Asch <vincent.vanasch@ua.ac.be>, Tom De Smedt <tom@organisms.be>
# License: GNU General Public License, see LICENSE.txt
### TREE #############################################################################################
# Implements a Sentence object to traverse sentence words, chunks and prepositions.
# This is probably what you will be working with when processing the output of the parser in Python.
# It is used internally in the PP-attacher and to generate XML and NLTK trees.
# Some basic terminology:
# - sentence: the basic unit of writing, expected to have a subject and a predicate.
# - word: a string of characters that expresses a meaningful concept.
# - token: a specific word with grammatical tags, the word "can" can appear many times in the sentence.
# - chunk: a phrase; a group of words that contains a single thought; phrases make up sentences.
# - argument: a phrase that is related to a verb in a clause, i.e. subject and object.
# - clause: subject + predicate.
# - subject: the person/thing the sentence is about, usually a noun phrase (NP); "[the oval] is white".
# - predicate: the remainder of the sentence tells us what the subject does; "the oval [is white]".
# - object: the person/thing affected by the action; "the shapes form [a circle]".
# - preposition: temporal, spatial or logical relationship; "the oval is [below the rectangle]".
# - copula: a word used to link subject and predicate, typically the verb "to be".
# - lemma: canonical form of a word: "run","runs", "running" are part of a lexeme, "run" is the lemma.
# - pos: part-of-speech, the role that a word or phrase plays in a sentence, e.g. NN (noun).
# Sentence is meant for analysis - no parsing functionality should be added to it.
# All parsing takes place in the parse() function.
try:
from config import SLASH
from config import WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA
MBSP = True
except:
SLASH, WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA = \
"&slash;", "word", "part-of-speech", "chunk", "preposition", "relation", "anchor", "lemma"
MBSP = False
IOB = "IOB" # The I- part of I-NP.
ROLE = "role" # The SBJ part of NP-SBJ-1.
# IOB chunk tags:
BEGIN = "B" # Start of chunk, as in B-NP.
INSIDE = "I" # Inside a chunk, as in I-NP.
OUTSIDE = "O" # Outside a chunk (punctuation etc.)
### LIST FUNCTIONS ###################################################################################
def find(function, list):
""" Returns the first item in the list for which function(item) is True, None otherwise.
"""
for item in list:
if function(item) == True:
return item
_zip = zip
def zip(*lists, **default):
""" Returns a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables.
The default value is appended to the shortest list to match the length of the longest list.
"""
m = max([len(x) for x in lists])
return _zip(*[x+[default.get("default", None)]*(m-len(x)) for x in lists])
def unzip(index, list):
""" Returns the item at the given index from inside each tuple in the list.
"""
return [item[index] for item in list]
def intersects(list1, list2):
""" Returns True if list1 and list2 have at least one item in common.
"""
return find(lambda item: item in list1, list2) is not None
def unique(list):
""" Returns a copy of the list with unique items, in-order.
"""
unique, v = [], {}
for item in list:
if item in v: continue
unique.append(item); v[item]=1
return unique
class dynamic_map(list):
""" Behaves as lambda map() by executing a function on each item in the set.
Different from map() it does not compute a list copy,
but fetches items or an iterator on the fly.
"""
def __init__(self, function=lambda item: item, set=[]):
self.set = set
self.function = function
def __repr__(self):
return repr([item for item in self])
def __getitem__(self, index):
return self.function(self.set[index])
def __len__(self):
return len(self.set)
def __iter__(self):
i = 0
while i < len(self.set):
yield self.function(self.set[i])
i+=1
### SENTENCE #########################################################################################
encode_entities = lambda string: string.replace("/", SLASH)
decode_entities = lambda string: string.replace(SLASH, "/")
#--- WORD --------------------------------------------------------------------------------------------
class Word:
def __init__(self, sentence, string, lemma=None, type=None, index=0):
""" A word in the sentence.
- lemma : base form of the word, e.g. "was" => "be".
- type : the part-of-speech tag, e.g. "NN" => a noun.
- chunk : the chunk (or phrase) this word belongs to.
- index : the index in the sentence.
"""
try: string = string.decode("utf-8") # ensure Unicode
except:
pass
self.sentence = sentence
self.index = index
self.string = string # laughed
self.lemma = lemma # laugh
self.type = type # VB
self.chunk = None # Chunk object this word belongs to (e.g. VP).
self.pnp = None # PNP chunk object this word belongs to.
# word.chunk and word.pnp are set in chunk.append().
self.custom_tags = Tags(self) # Additional user-defined tags (e.g. {SENTIMENT: "joy"}).
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
w.custom_tags = Tags(w, items=self.custom_tags)
return w
@property
def tag(self):
return self.type
pos = part_of_speech = 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__()
# Note: IOB-tags and relations tags can differ from the original MBSP output:
# - B-VP N-NP I-NP <=> I-VP B-NP I-NP
# - PP-CLR-1 NP-CLR-1 <=> PP-CLR-1 PP-CLR-1
# This has no influence when creating a new tree from repr(Sentence).
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 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
# User-defined tags are available as Word.tag attributes.
def __getattr__(self, tag):
if tag in self.__dict__.get("custom_tags",()):
return self.__dict__["custom_tags"][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 __unicode__(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)
class Tags(dict):
def __init__(self, word, items=[]):
# A dictionary of custom word tags.
# If a new tag is introduced, ensures that is also in Word.sentence.token.
# This way it won't be forgotten when exporting/importing as XML.
dict.__init__(self, items)
self.word = word
def __setitem__(self, k, v):
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:
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 part-of-speech tag, e.g. "NP" => a noun phrase, like "the big statue".
- role: the function of the phrase, e.g. "SBJ" => sentence subject.
- relation: an id shared with other phrases (e.g. linking subject to object, ...)
"""
# A chunk can have multiple roles and/or relations in the sentence.
# Role and relation can therefore also be passed as a list.
a, b = relation, role
if not isinstance(a, (list,tuple)):
a = isinstance(b,(list,tuple)) and [a for x in b] or [a]
if not isinstance(b, (list,tuple)):
b = isinstance(a,(list,tuple)) and [b for x in a] or [b]
relations = [x for x in zip(a,b) if x[0] is not None or x[1] is not None]
self.sentence = sentence
self.words = []
self.type = type # NP, VP, ADJP ...
self.relations = relations # 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 = Conjunctions(self)
self._modifiers = None
self.extend(words)
def extend(self, words):
[self.append(word) for word in words]
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__()
@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 tag(self):
return self.type
pos = part_of_speech = tag
@property
def head(self):
""" The head of the chunk (i.e. the last word in the chunk).
"""
return self.words[-1]
@property
def relation(self):
""" The first relation id of the chunk (i.e. chunk.relations[(2,OBJ), (3,OBJ)])] => 2).
"""
return len(self.relations) > 0 and self.relations[0][0] or None
@property
def role(self):
""" The first role of the chunk (i.e. chunk.relations[(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):
""" A list of all the chunks that have 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.
For anchor chunks, it has the "A" prefix (e.g. "A1").
For PNP's attached to an anchor (or chunks inside the PNP), it has the "P" prefix (e.g. "P1").
A chunk inside a PNP can be both anchor and attachment (e.g. "P1-A2"), as in:
"stand/A1 in/P1 front/P1-A2 of/P2 people/P2".
"""
id = ""
# Yields all anchor tags (e.g. A1, P1, ...) of the given chunk.
f = lambda ch: 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 modifiers(self):
""" For verb phrases (VP), yields a list of nearby adjectives and adverbs with no clear role:
"the page is [cluttered] with red ovals", "maybe it is green" != "it is green", etc.
"""
if self._modifiers is None:
# Modifiers have not been initialized yet:
# 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.
We can use this to relate adverbs and adjectives to verbs.
For example: "the page [is] [cluttered] with ovals": is <=> cluttered.
"""
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 (of the given type) in the sentence.
"""
i = self.stop
while i < len(self.sentence):
if self.sentence[i].chunk is not None and type in (self.sentence[i].chunk.type, None):
return self.sentence[i].chunk
i += 1
def previous(self, type=None):
""" Returns the next previous (of the given type) in the sentence.
"""
i = self.start-1
while i > 0:
if self.sentence[i].chunk is not None and type in (self.sentence[i].chunk.type, None):
return self.sentence[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 u" ".join([word.string for word in self.words])
def __unicode__(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)
# Used in 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 used to identify a prepositional noun phrase.
When the Sentence class has functionality for PP-attachment,
PNPChunk.anchor will point to the phrase clarified by the preposition,
for example: "I eat pizza with a fork" => "eat" + "with a fork".
"""
self.anchor = None # The anchor chunk (e.g. "eat pizza with fork" => "eat" is anchor of "with fork").
self.chunks = [] # The chunks that make up 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:
# Collect the chunks that are part of the preposition.
# This usually involves a PP and a NP chunk ("below/PP the surface/NP"),
# where the PP is the preposition that can be attached
# to another phrase, e.g. "What goes on below the surface":
# "below the surface" <=> "go".
word.chunk.pnp = self
if word.chunk not in self.chunks:
self.chunks.append(word.chunk)
@property
def preposition(self):
""" The first chunk in the prepositional noun phrase, which should be a PP-type chunk.
PP-chunks are words such as "with" or "underneath".
"""
return self.chunks[0]
pp = preposition
@property
def phrases(self):
return self.chunks
def guess_anchor(self):
""" Returns a possible anchor chunk for this prepositional noun phrase (without a PP-attacher).
Often, the nearest verb phrase is a good guess.
"""
return self.nearest("VP")
#--- CONJUNCTION -------------------------------------------------------------------------------------
CONJUNCT = AND = "AND"
DISJUNCT = OR = "OR"
class Conjunctions(list):
def __init__(self, chunk):
""" A chunk property containing other chunks participating in a conjunction,
e.g. "clear skies AND sunny beaches".
Each item in the list is a (chunk, conjunction)-tuple, with conjunction either AND or OR.
"""
list.__init__(self)
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, unicode) and hasattr(string, "tags")
class Sentence:
def __init__(self, string="", token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA], language="en"):
""" A search object for sentence words, chunks and prepositions.
The input is a tagged string from MBSP.parse().
The order in which token tags appear can be specified.
"""
# Extract token format from TokenString if possible.
if _is_tokenstring(string):
token, language = string.tags, getattr(string, "language", language)
# Ensure Unicode.
if isinstance(string, str):
for encoding in (("utf-8",), ("windows-1252",), ("utf-8", "ignore")):
try: string = string.decode(*encoding)
except:
pass
self.parent = None # Slices will refer to the sentence they are part of.
self.text = None # Text object this sentence is part of.
self.language = language
self.id = _uid()
self.token = list(token)
self.words = []
self.chunks = [] # Words grouped in chunk ranges.
self.pnp = [] # Words grouped in prepositional noun phrase ranges.
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":{} }
for chars in string.split(" "):
if len(chars) > 0:
# Split the slash-formatted token into the separate tags according to the given order.
# Append Word and Chunk objects according to the token's tags.
self.append(*self.parse_token(chars, token))
@property
def word(self):
return self.words
@property
def lemmata(self):
return dynamic_map(lambda w: w.lemma, self.words)
#return [word.lemma for word in self.words]
lemma = lemmata
@property
def parts_of_speech(self):
return dynamic_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 self.relations["SBJ"].values()
@property
def objects(self):
return self.relations["OBJ"].values()
@property
def verbs(self):
return 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 and attaches words, chunks, prepositions.
The tagged tokens from the parser's output simply need to be split and passed to Sentence.append().
- word : the current word.
- lemma : lemmatized 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 (BEGIN- 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) # Appends a new Word object.
self._do_chunk(chunk, role, relation, iob) # Appends a new Chunk, or adds the last word to the last chunk.
self._do_relation()
self._do_pnp(pnp, anchor)
self._do_anchor(anchor)
self._do_custom(custom)
self._do_conjunction()
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: word, part-of-speech, (IOB-)chunk, (IOB-)preposition,
chunk(-relation)(-role), anchor, lemma, separated by slashes.
As in:
I/PRP/B-NP/O/NP-SBJ-1/O/i
eat/VBP/B-VP/O/VP-1/A1/eat
pizza/NN/B-NP/O/NP-OBJ-1/O/pizza
with/IN/B-PP/B-PNP/PP/P1/with
a/DT/B-NP/I-PNP/NP/P1/a
fork/NN/I-NP/I-PNP/NP/P1/fork
././O/O/O/O/.
Returns a (word, lemma, type, chunk, role, relation, preposition, anchor, iob, custom)-tuple,
i.e. you can do Sentence.append(*Sentence.parse_token("airplane/NN"))
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 }
custom = [tag for tag in tags if tag not in p] # Tags for custom parsers, e.g. a SENTIMENT-tag.
p.update(dict.fromkeys(custom, None))
# Split the slash-formatted token into the separate tags according to the given order.
# Convert &slash; characters (usually in words and lemmata).
# Assume None for missing tags (except the word itself, which defaults to an empty string).
token = token.split("/")
for i in range(min(len(token), len(tags))):
if token[i] != OUTSIDE \
or tags[i] in (WORD, LEMMA): # In "O is part of the alphabet" => "O" != OUTSIDE.
p[tags[i]] = decode_entities(token[i])
# Split I/B prefix from the chunk tag:
# B- marks the start of a new chunk, I- marks inside of a chunk.
if p[CHUNK] is not None:
x = p[CHUNK].split("-")
if len(x) == 2: p[CHUNK] = x[1]; p[IOB] = x[0] # B-NP
if len(x) == 1: p[CHUNK] = x[0] # NP
# Split the role from the relation:
# NP-SBJ-1 => relation id is 1 and role SBJ, VP-1 => relation id is 1 and no role.
# Note: tokens can 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])
# We can derive 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 not p[CHUNK] and ch != OUTSIDE:
p[CHUNK] = ch
self._previous = p
# Return the tags in the same order as the parameters for Sentence.append().
custom = dict([(tag, p[tag]) for tag in custom])
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 role and relation id from the token relation tag.
About 20 percent of sentences parsed by MBSP have chunks with multiple relations:
- VP => VP, [], []
- VP-1 => VP, [1], [None]
- 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, [], []
for s in tag.split("*"):
if ";" in s:
id = ([None]+s.split("-"))[-1] # NP-SBJ;NP-OBJ-1 => 1 relates to both SBJ and OBJ.
id = id is not None and "-"+id or ""
s = s.replace(";", id+";")
s = s.split(";")
else:
s = [s]
for s in s:
s = s.split("-")
if len(s) == 1: chunk = s[0]
if len(s) == 2: chunk = s[0]; relation.append(s[1]); role.append(None)
if len(s) >= 3: chunk = s[0]; relation.append(s[2]); role.append(s[1])
for i, x in enumerate(relation):
if x is not None:
try: relation[i] = int(x)
except: # Correct ADJP-PRD => ADJP, [PRD], [None] to ADJP, [None], [PRD].
relation[i], role[i] = None, x
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 == "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):
""" Either 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.
"""
O = (None, OUTSIDE)
if type in O and relation in O and role in O:
return
if len(self.chunks) > 0 \
and self.chunks[-1].type == type \
and self._relation == (relation, role) \
and not iob == BEGIN \
and not self.words[-2].chunk is None: # As for me, I'm off => me + I are 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 len(self.chunks) > 0:
ch = self.chunks[-1]
for ch_relation, ch_role in [x for x in ch.relations if x[1] in ("SBJ", "OBJ")]:
self.relations[ch_role][ch_relation] = ch
if ch.type in ("VP",):
self.relations[ch.type][ch.relation] = ch
def _do_pnp(self, pnp, anchor=None):
""" Attach prepositional noun phrases.
We can identify PNP's from either the PNP tag or the P-attachment tag.
This does not yet determine the PP-anchor, only groups words in a PNP chunk.
"""
P = find(lambda x: x.startswith("P"), anchor and anchor.split("-") or [])
if pnp and pnp.endswith("PNP") or P is not None:
if (pnp and pnp != "O" \
and len(self.pnp) > 0 \
and not pnp.startswith("B") \
and not self.words[-2].pnp is None \
) or (P is not None and P == self._attachment):
self.pnp[-1].append(self.words[-1])
else:
ch = PNPChunk(self, [self.words[-1]], type="PNP")
self.pnp.append(ch)
self._attachment = P
def _do_anchor(self, anchor):
""" Collect preposition anchors and attachments in a dictionary as we iterate words.
Once the dictionary has an entry for both the anchor and the attachment we can link them.
"""
for x in (anchor and anchor.split("-") or []):
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.
"""
self.words[-1].custom_tags = Tags(self.words[-1], custom)
def _do_conjunction(self):
""" Attach conjunctions.
CC-words like "and" / "or" between two chunks indicate a conjunction.
"""
if len(self.words) > 2 and self.words[-2].type == "CC":
if self.words[-2].chunk is None:
cc = self.words[-2].string.lower() == "and" and AND or OR
ch1 = self.words[-3].chunk
ch2 = self.words[-1].chunk
if ch1 is not None and ch2 is not None:
ch1.conjunctions.append(ch2, cc)
ch2.conjunctions.append(ch1, cc)
def get(self, index, tag=LEMMA):
""" Returns a tag for the word at the given index.
The tag can be WORD, LEMMA, POS, CHUNK, PNP, RELATION, ROLE, ANCHOR or a custom word tag.
"""
if tag == WORD:
return self.words[index]
if tag == LEMMA:
return self.words[index].lemma
if tag == POS:
return self.words[index].type
if tag == CHUNK:
return self.words[index].chunk
if tag == PNP:
return self.words[index].pnp
if tag == REL:
ch = self.words[index].chunk; return ch and ch.relation
if tag == ROLE:
ch = self.words[index].chunk; return ch and ch.role
if tag == ANCHOR:
ch = self.words[index].pnp; return ch and ch.anchor
if tag in self.words[index].custom_tags:
return self.words[index].custom_tags[tag]
return None
def loop(self, *tags):
""" Iterates over the tags in the entire Sentence,
e.g. Sentence.loop(POS, LEMMA) yields tuples of the part-of-speech tags and lemmata.
Possible tags: WORD, LEMMA, POS, CHUNK, PNP, RELATION, ROLE, ANCHOR or a custom word tag.
Any order or combination of tags can be supplied.
"""
for i in range(len(self.words)):
yield tuple([self.get(i, tag=tag) for tag in tags])
def indexof(self, value, tag=WORD):
""" Returns the indices of tokens in the sentence where the given token tag equals the string.
The string can contain a wildcard "*" at the end (this way "NN*" will match "NN" and "NNS").
The tag can be WORD, LEMMA, POS, CHUNK, PNP, RELATION, ROLE, ANCHOR or a custom word tag.
For example: Sentence.indexof("VP", tag=CHUNK)
returns the indices of all the words that are part of a VP chunk.
"""
match = lambda a, b: a.endswith("*") and b.startswith(a[:-1]) or a==b
indices = []
for i in range(len(self.words)):
if match(value, unicode(self.get(i, tag))):
indices.append(i)
return indices
def slice(self, start, stop):
""" Returns a portion of the sentence from word start index to word stop index.
The returned slice is a subclass of Sentence and a deep copy.
"""
s = Slice(token=self.token, language=self.language)
for i, word in enumerate(self.words[start:stop]):
# The easiest way to copy (part of) a sentence
# is by unpacking all of the token tags and passing them to Sentence.append().
p0 = word.string # WORD
p1 = word.lemma # LEMMA
p2 = word.type # POS
p3 = word.chunk is not None and word.chunk.type or None # CHUNK
p4 = word.pnp is not None and "PNP" or None # PNP
p5 = word.chunk is not None and unzip(0, word.chunk.relations) or None # REL
p6 = word.chunk is not None and unzip(1, word.chunk.relations) or None # ROLE
p7 = word.chunk and word.chunk.anchor_id or None # ANCHOR
p8 = word.chunk and word.chunk.start == start+i and BEGIN or None # IOB
p9 = word.custom_tags # User-defined tags.
# If the given range does not contain the chunk head, remove the chunk tags.
if word.chunk is not None and (word.chunk.stop > stop):
p3, p4, p5, p6, p7, p8 = None, None, None, None, None, None
# If the word starts the preposition, add the IOB B-prefix (i.e. B-PNP).
if word.pnp is not None and word.pnp.start == start+i:
p4 = BEGIN+"-"+"PNP"
# If the given range does not contain the entire PNP, remove the PNP tags.
# The range must contain the entire PNP,
# since it starts with the PP and ends with the chunk head (and is meaningless without these).
if word.pnp is not None and (word.pnp.start < start or word.chunk.stop > stop):
p4, p7 = None, None
s.append(word=p0, lemma=p1, type=p2, chunk=p3, pnp=p4, relation=p5, role=p6, anchor=p7, iob=p8, custom=p9)
s.parent = self
s.start = start
return s
def copy(self):
return self.slice(0, len(self))
def chunked(self):
return chunked(self)
def constituents(self, pnp=False):
""" Returns an in-order list of the top Chunk and Word objects.
With pnp=True, also contains PNPChunk objects whenever possible.
"""
a = []
for word in self.words:
if pnp and word.pnp is not None:
if len(a) == 0 or a[-1] != word.pnp:
a.append(word.pnp)
elif word.chunk is not None:
if len(a) == 0 or a[-1] != word.chunk:
a.append(word.chunk)
else:
a.append(word)
return a
# Sentence.string and unicode(Sentence) are Unicode strings.
# repr(Sentence) is a Python strings (with Unicode characters encoded).
@property
def string(self):
return u" ".join([word.string for word in self])
def __unicode__(self):
return self.string
def __repr__(self):
return "Sentence(%s)" % repr(" ".join(["/".join(word.tags) for word in self.words]).encode("utf-8"))
def __eq__(self, other):
if not isinstance(other, Sentence): return False
return len(self) == len(other) \
and repr(self) == repr(other)
@property
def xml(self):
""" The sentence in XML format.
"""
return parse_xml(self, tab="\t", id=self.id or "")
@classmethod
def from_xml(self, xml):
s = parse_string(xml)
return Sentence(s.split("\n")[0], token=s.tags, language=s.language)
def nltk_tree(self):
""" The sentence as an nltk.tree object.
"""
return nltk_tree(self)
class Slice(Sentence):
pass
#-----------------------------------------------------------------------------------------------------
# s = split(parse("black cats and white dogs"))
# s.words => [Word('black/JJ'), Word('cats/NNS'), Word('and/CC'), Word('white/JJ'), Word('dogs/NNS')]
# s.chunks => [Chunk('black cats/NP'), Chunk('white dogs/NP')]
# s.constituents(s) => [Chunk('black cats/NP'), Word('and/CC'), Chunk('white dogs/NP')]
# chunked(s) => [Chunk('black cats/NP'), Chink('and/O'), Chunk('white dogs/NP')]
def chunked(sentence):
""" Returns a list of Chunk and Chink objects from the given sentence.
Chink is a subclass of Chunk used for words that have Word.chunk==None
(e.g. punctuation marks, conjunctions).
"""
# For example: to create an instance that uses the head of previous chunks as feature.
# Doing this with Sentence.chunks would lose the punctuation and conjunction words
# (Sentence.chunks only has Chunk objects) which can be useful as feature.
chunks = []
for word in sentence:
if word.chunk is not None:
if len(chunks) == 0 or chunks[-1] != word.chunk:
chunks.append(word.chunk)
else:
ch = Chink(sentence)
ch.append(word.copy(ch))
chunks.append(ch)
return chunks
#--- TEXT --------------------------------------------------------------------------------------------
class Text(list):
def __init__(self, string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA], language="en", encoding="utf-8"):
""" A list of Sentence objects parsed from the given string.
The string is the unicode return value from MBSP.parse().
"""
self.encoding = encoding
# Extract token format from TokenString if possible.
if _is_tokenstring(string):
token, language = string.tags, getattr(string, "language", language)