/
phrase.go
83 lines (62 loc) · 1.51 KB
/
phrase.go
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
package rumorph
import (
"errors"
"fmt"
"github.com/mihard/ru-morph/kind"
"regexp"
"strings"
)
type Phrase struct {
original string
origWords []string
words []kind.IWord
gen string
}
func MakePhrase(original string) (*Phrase, error) {
words := regexp.MustCompile("[—\\s-]+").Split(original, 10)
p := &Phrase{original: original, origWords: words, words: []kind.IWord{}}
if err := p.validate(); err != nil {
return nil, err
}
return p, nil
}
func (p *Phrase) AddWord(w kind.IWord) {
p.words = append(p.words, w)
}
func (p *Phrase) GetWordsOfOriginal() []string {
return p.origWords
}
func (p *Phrase) Locative() string {
locative := p.original
fg := ""
pLen := len(p.words)
for i, w := range p.words {
l, changed := w.Locative(fg)
if changed {
fg = w.Gen()
}
locative = strings.Replace(locative, w.Word(), l, 10)
if pLen > 1 && i == pLen-1 && w.Gen() == kind.GEN_MIDDLE && !changed {
return p.locativeForUnchangableMiddleGenNouns()
}
}
return locative
}
func (p *Phrase) locativeForUnchangableMiddleGenNouns() string {
locative := p.original
fg := kind.ENFORCED_ORIGINAL
for _, w := range p.words {
l, _ := w.Locative(fg)
locative = strings.Replace(locative, w.Word(), l, 10)
}
return locative
}
func (p *Phrase) validate() error {
vrx := regexp.MustCompile("^[0-9А-ЯЁа-яё]+$")
for _, w := range p.origWords {
if !vrx.MatchString(w) {
return errors.New(fmt.Sprintf("The word '%s' contains one or more not-Cyrillic characters", w))
}
}
return nil
}