|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Clause segmenter |
| 4 | +""" |
| 5 | +from typing import List |
| 6 | + |
| 7 | +import pycrfsuite |
| 8 | +from pythainlp.corpus import get_corpus_path |
| 9 | +from pythainlp.tag import pos_tag |
| 10 | + |
| 11 | + |
| 12 | +def _doc2features(doc, i): |
| 13 | + # features from current word |
| 14 | + curr_word = doc[i][0] |
| 15 | + curr_pos = doc[i][1] |
| 16 | + features = { |
| 17 | + "word.curr_word": curr_word, |
| 18 | + "word.curr_isspace": curr_word.isspace(), |
| 19 | + "word.curr_isdigit": curr_word.isdigit(), |
| 20 | + "word.curr_postag": curr_pos, |
| 21 | + } |
| 22 | + |
| 23 | + # features from previous word |
| 24 | + if i > 0: |
| 25 | + prev_word = doc[i - 1][0] |
| 26 | + prev_pos = doc[i - 1][1] |
| 27 | + features["word.prev_word"] = prev_word |
| 28 | + features["word.prev_isspace"] = prev_word.isspace() |
| 29 | + features["word.prev_isdigit"] = prev_word.isdigit() |
| 30 | + features["word.prev_postag"] = prev_pos |
| 31 | + else: |
| 32 | + features["BOS"] = True # Beginning of Sequence |
| 33 | + |
| 34 | + # features from next word |
| 35 | + if i < len(doc) - 1: |
| 36 | + next_word = doc[i + 1][0] |
| 37 | + next_pos = doc[i + 1][1] |
| 38 | + features["word.next_word"] = next_word |
| 39 | + features["word.next_isspace"] = next_word.isspace() |
| 40 | + features["word.next_isdigit"] = next_word.isdigit() |
| 41 | + features["word.next_postag"] = next_pos |
| 42 | + else: |
| 43 | + features["EOS"] = True # End of Sequence |
| 44 | + |
| 45 | + return features |
| 46 | + |
| 47 | + |
| 48 | +def _extract_features(doc): |
| 49 | + return [_doc2features(doc, i) for i in range(len(doc))] |
| 50 | + |
| 51 | + |
| 52 | +_CORPUS_NAME = "lst20-cls" |
| 53 | +tagger = pycrfsuite.Tagger() |
| 54 | +tagger.open(get_corpus_path(_CORPUS_NAME)) |
| 55 | + |
| 56 | + |
| 57 | +def segment(doc: List[str]) -> List[List[str]]: |
| 58 | + word_tags = pos_tag(doc, corpus="lst20") |
| 59 | + features = _extract_features(word_tags) |
| 60 | + word_markers = list(zip(doc, tagger.tag(features))) |
| 61 | + |
| 62 | + clauses = [] |
| 63 | + temp = [] |
| 64 | + len_doc = len(doc) - 1 |
| 65 | + for i, word_marker in enumerate(word_markers): |
| 66 | + word, marker = word_marker |
| 67 | + if marker == "E_CLS" or i == len_doc: |
| 68 | + temp.append(word) |
| 69 | + clauses.append(temp) |
| 70 | + temp = [] |
| 71 | + else: |
| 72 | + temp.append(word) |
| 73 | + |
| 74 | + return clauses |
0 commit comments