aboutsummaryrefslogtreecommitdiffstats
path: root/fsa/src/main/java/com/yahoo/fsa/segmenter/Segmenter.java
blob: f0ccd100a1e34935fad5e028bdcb15cee17e084e (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.fsa.segmenter;

import java.util.LinkedList;
import java.util.ListIterator;

import com.yahoo.fsa.FSA;

/**
 * API for accessing the Segmenter automata.
 *
 * @author Peter Boros
 */
public class Segmenter {

  private final FSA fsa;

  public Segmenter(FSA fsa) {
    this.fsa = fsa;
  }

  public Segmenter(String filename) {
    fsa = new FSA(filename, "utf-8");
  }

  public Segmenter(String filename, String charsetname) {
    fsa = new FSA(filename, charsetname);
  }

  public boolean isOk() {
    return fsa.isOk();
  }

  public Segments segment(String input) {
    String[] tokens = input.split("\\s");
    return segment(tokens);
  }

  private class Detector {

    final FSA.State state;
    final int index;

    public Detector(FSA.State s, int i) {
      state = s;
      index = i;
    }

    public FSA.State state()
    {
      return state;
    }

    public int index()
    {
      return index;
    }

  }

  public Segments segment(String[] tokens) {
    Segments segments = new Segments(tokens);
    LinkedList<Detector> detectors = new LinkedList<>();

    int i=0;


    while(i<tokens.length){
      detectors.add(new Detector(fsa.getState(), i));

      ListIterator<Detector> det_it = detectors.listIterator();
      while(det_it.hasNext()){
        Detector d = det_it.next();
        d.state().deltaWord(tokens[i]);
        if(d.state().isFinal()){
          segments.add(new Segment(d.index(),i+1,d.state().data().getInt(0)));
        }

        if(!d.state().isValid()){
          det_it.remove();
        }
      }
      i++;
    }

    return segments;
  }

}