jmwang66
2023-01-16 12a7adfdf3dd4f80b5d3a51cfc4eecc84eaa7c64
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
#!/usr/bin/env python
import re
import numpy as np
 
def forward_segment(text, seg_dict):
    word_list = []
    i = 0
    while i < len(text):
        longest_word = text[i]
        for j in range(i + 1, len(text) + 1):
            word = text[i:j]
            if word in seg_dict:
                if len(word) > len(longest_word):
                    longest_word = word
        word_list.append(longest_word)
        i += len(longest_word)
    return word_list
 
def seg_tokenize(txt, seg_dict):
    out_txt = ""
    pattern = re.compile(r"([\u4E00-\u9FA5A-Za-z0-9])")
    for word in txt:
        if pattern.match(word):
            if word in seg_dict:
                out_txt += seg_dict[word] + " "
            else:
                out_txt += "<unk>" + " "
        else:
            continue
    return out_txt.strip().split()
 
def tokenize(data,
             vocab=None,
             seg_dict=None):
    assert "text" in data
    assert isinstance(vocab, dict)
    text = data["text"]
    token = []
 
    if seg_dict is not None:
        assert isinstance(seg_dict, dict)
        txt = forward_segment("".join(text).lower(), seg_dict)
        text = seg_tokenize(txt, seg_dict)
    
    for x in text:
        if x in vocab:
            token.append(vocab[x])
        else:
            token.append(vocab['<unk>'])
 
    data["text"] = np.array(token)
    return data