Returns an NLTK nltk.tree.Tree object from the given Sentence. The NLTK module should be on the search path somewhere.
(sentence)
| 1474 | ### NLTK TREE ###################################################################################### |
| 1475 | |
| 1476 | def nltk_tree(sentence): |
| 1477 | """ Returns an NLTK nltk.tree.Tree object from the given Sentence. |
| 1478 | The NLTK module should be on the search path somewhere. |
| 1479 | """ |
| 1480 | from nltk import tree |
| 1481 | def do_pnp(pnp): |
| 1482 | # Returns the PNPChunk (and the contained Chunk objects) in NLTK bracket format. |
| 1483 | s = ' '.join([do_chunk(ch) for ch in pnp.chunks]) |
| 1484 | return '(PNP %s)' % s |
| 1485 | |
| 1486 | def do_chunk(ch): |
| 1487 | # Returns the Chunk in NLTK bracket format. Recurse attached PNP's. |
| 1488 | s = ' '.join(['(%s %s)' % (w.pos, w.string) for w in ch.words]) |
| 1489 | s+= ' '.join([do_pnp(pnp) for pnp in ch.attachments]) |
| 1490 | return '(%s %s)' % (ch.type, s) |
| 1491 | |
| 1492 | T = ['(S'] |
| 1493 | v = [] # PNP's already visited. |
| 1494 | for ch in sentence.chunked(): |
| 1495 | if not ch.pnp and isinstance(ch, Chink): |
| 1496 | T.append('(%s %s)' % (ch.words[0].pos, ch.words[0].string)) |
| 1497 | elif not ch.pnp: |
| 1498 | T.append(do_chunk(ch)) |
| 1499 | #elif ch.pnp not in v: |
| 1500 | elif ch.pnp.anchor is None and ch.pnp not in v: |
| 1501 | # The chunk is part of a PNP without an anchor. |
| 1502 | T.append(do_pnp(ch.pnp)) |
| 1503 | v.append(ch.pnp) |
| 1504 | T.append(')') |
| 1505 | return tree.bracket_parse(' '.join(T)) |
| 1506 | |
| 1507 | ### GRAPHVIZ DOT ################################################################################### |
| 1508 |