| 239 | #--- CHUNK ----------------------------------------------------------------------------------------- |
| 240 | |
| 241 | class Chunk(object): |
| 242 | |
| 243 | def __init__(self, sentence, words=[], type=None, role=None, relation=None): |
| 244 | """ A list of words that make up a phrase in the sentence. |
| 245 | - type: the phrase tag; "NP" => a noun phrase (e.g., "the black cat"). |
| 246 | - role: the function of the phrase; "SBJ" => sentence subject. |
| 247 | - relation: an id shared with other phrases, linking subject to object in the sentence. |
| 248 | """ |
| 249 | # A chunk can have multiple roles or relations in the sentence, |
| 250 | # so role and relation can also be given as lists. |
| 251 | a, b = relation, role |
| 252 | if not isinstance(a, (list, tuple)): |
| 253 | a = isinstance(b, (list, tuple)) and [a for x in b] or [a] |
| 254 | if not isinstance(b, (list, tuple)): |
| 255 | b = isinstance(a, (list, tuple)) and [b for x in a] or [b] |
| 256 | relations = [x for x in zip(a,b) if x[0] is not None or x[1] is not None] |
| 257 | self.sentence = sentence |
| 258 | self.words = [] |
| 259 | self.type = type # NP, VP, ADJP ... |
| 260 | self.relations = relations # NP-SBJ-1 => [(1, SBJ)] |
| 261 | self.pnp = None # PNP chunk object this chunk belongs to. |
| 262 | self.anchor = None # PNP chunk's anchor. |
| 263 | self.attachments = [] # PNP chunks attached to this anchor. |
| 264 | self.conjunctions = Conjunctions(self) |
| 265 | self._modifiers = None |
| 266 | self._head = lambda self: self.words[-1] |
| 267 | self.extend(words) |
| 268 | |
| 269 | def extend(self, words): |
| 270 | [self.append(word) for word in words] |
| 271 | |
| 272 | def append(self, word): |
| 273 | self.words.append(word) |
| 274 | word.chunk = self |
| 275 | |
| 276 | def __getitem__(self, index): |
| 277 | return self.words[index] |
| 278 | def __len__(self): |
| 279 | return len(self.words) |
| 280 | def __iter__(self): |
| 281 | return self.words.__iter__() |
| 282 | |
| 283 | def _get_tag(self): |
| 284 | return self.type |
| 285 | def _set_tag(self, v): |
| 286 | self.type = v |
| 287 | |
| 288 | tag = pos = part_of_speech = property(_get_tag, _set_tag) |
| 289 | |
| 290 | @property |
| 291 | def start(self): |
| 292 | return self.words[0].index |
| 293 | @property |
| 294 | def stop(self): |
| 295 | return self.words[-1].index + 1 |
| 296 | @property |
| 297 | def range(self): |
| 298 | return range(self.start, self.stop) |
no outgoing calls
no test coverage detected
searching dependent graphs…