| 650 | GREEDY = "greedy" |
| 651 | |
| 652 | class Pattern(object): |
| 653 | |
| 654 | def __init__(self, sequence=[], *args, **kwargs): |
| 655 | """ A sequence of constraints that matches certain phrases in a sentence. |
| 656 | The given list of Constraint objects can contain nested lists (groups). |
| 657 | """ |
| 658 | # Parse nested lists and tuples from the sequence into groups. |
| 659 | # [DT [JJ NN]] => Match.group(1) will yield the JJ NN sequences. |
| 660 | def _ungroup(sequence, groups=None): |
| 661 | for v in sequence: |
| 662 | if isinstance(v, (list, tuple)): |
| 663 | if groups is not None: |
| 664 | groups.append(list(_ungroup(v, groups=None))) |
| 665 | for v in _ungroup(v, groups): |
| 666 | yield v |
| 667 | else: |
| 668 | yield v |
| 669 | self.groups = [] |
| 670 | self.sequence = list(_ungroup(sequence, groups=self.groups)) |
| 671 | # Assign Constraint.index: |
| 672 | i = 0 |
| 673 | for constraint in self.sequence: |
| 674 | constraint.index = i; i+=1 |
| 675 | # There are two search modes: STRICT and GREEDY. |
| 676 | # - In STRICT, "rabbit" matches only the string "rabbit". |
| 677 | # - In GREEDY, "rabbit|NN" matches the string "rabbit" tagged "NN". |
| 678 | # - In GREEDY, "rabbit" matches "the big white rabbit" (the entire chunk is a match). |
| 679 | # - Pattern.greedy(chunk, constraint) determines (True/False) if a chunk is a match. |
| 680 | self.strict = kwargs.get("strict", STRICT in args and not GREEDY in args) |
| 681 | self.greedy = kwargs.get("greedy", lambda chunk, constraint: True) |
| 682 | |
| 683 | def __iter__(self): |
| 684 | return iter(self.sequence) |
| 685 | def __len__(self): |
| 686 | return len(self.sequence) |
| 687 | def __getitem__(self, i): |
| 688 | return self.sequence[i] |
| 689 | |
| 690 | @classmethod |
| 691 | def fromstring(cls, s, *args, **kwargs): |
| 692 | """ Returns a new Pattern from the given string. |
| 693 | Constraints are separated by a space. |
| 694 | If a constraint contains a space, it must be wrapped in []. |
| 695 | """ |
| 696 | s = s.replace("\(", "&lparen;") |
| 697 | s = s.replace("\)", "&rparen;") |
| 698 | s = s.replace("\[", "[") |
| 699 | s = s.replace("\]", "]") |
| 700 | s = s.replace("\{", "&lcurly;") |
| 701 | s = s.replace("\}", "&rcurly;") |
| 702 | p = [] |
| 703 | i = 0 |
| 704 | for m in re.finditer(r"\[.*?\]|\(.*?\)", s): |
| 705 | # Spaces in a range encapsulated in square brackets are encoded. |
| 706 | # "[Windows Vista]" is one range, don't split on space. |
| 707 | p.append(s[i:m.start()]) |
| 708 | p.append(s[m.start():m.end()].replace(" ", "&space;")); i=m.end() |
| 709 | p.append(s[i:]) |
no outgoing calls
no test coverage detected
searching dependent graphs…