File size: 6,357 Bytes
def2a1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import string
import jieba
from tqdm import tqdm
import json
import numpy as np

stop_words = ['!', '……', '?', '的', '了', '嗯', '哦', '啊', '我', '你',
              '她', '他', '它', '在', '和', '吗', '呢', '可以', ',', '。',
              ':', ';']


def cut_sentence_by_word(sentence, stopwords):
    """
    按照单个字进行分词,需要处理单个英文字
    :param sentence:
    :param stopwords:
    :return:word_list
    """
    continue_words = string.ascii_lowercase + string.digits
    temp = ""
    result = []
    for word in sentence:
        if word in continue_words:
            temp += word
            continue
        if len(temp) > 0:
            result.append(temp)
            temp = ""
        result.append(word)
    if len(temp) > 0:
        result.append(temp)
    return [word for word in result if word not in stopwords]


def cut_sentence(sentence, stopwords):
    """
    按照词语进行分词
    :param sentence:
    :param stopwords:
    :return: words_list
    """
    return [word for word in jieba.lcut(sentence) if word not in stopwords]


def transfer_file_to_list(file_path):
    """

    :param file_path:
    :return:
    """
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = [line.rstrip().lower() for line in f]
    return lines


class TxtToIndex(object):
    def __init__(self, train_txt_path, test_txt_path, cuf_fn):
        """
        初始化
        :param train_txt_path: 原始训练数据地址
        :param test_txt_path: 原始测试数据地址
        :param cuf_fn: 分割函数,可以按字或者词分割
        """
        self.cut_fn = cuf_fn
        self._origin_train_data = transfer_file_to_list(train_txt_path)
        self._origin_test_data = transfer_file_to_list(test_txt_path)
        self._labels = []
        self._vocab = {}  # {"汀": 0, "哟": 1}
        self._create_vocab_and_labels()

    def _create_vocab_and_labels(self):
        vocab_length = 0
        label_set = set()  # 去重
        for i in tqdm(range(0, len(self._origin_train_data)), desc='Initializing'):
            sentence, label = self._origin_train_data[i].rsplit(sep=' ', maxsplit=1)
            label_set.add(label)
            word_list = self.cut_fn(sentence, stop_words)
            for word in word_list:
                if not self._vocab.get(word):
                    self._vocab[word] = vocab_length
                    vocab_length += 1

        self._labels = list(label_set)
        # 异常保护,如果原文中带<unk>或<pad>则用原文中的值
        self._vocab['<unk>'] = vocab_length if not self._vocab.get('<unk>', None) else self._vocab.get('<unk>')
        self._vocab['<pad>'] = vocab_length + 1 if not self._vocab.get('<unk>', None) else self._vocab.get('<unk>')

    def save_labels(self, label_path):
        """
        包括所有标签
        :param label_path: 保存地址
        """
        with open(label_path, 'w', encoding='utf-8') as f:
            for label in self._labels:
                f.writelines(label + '\n')

    def save_vocabulary(self, vocab_path):
        """
        包括train和dev的字典
        :param vocab_path: 保存地址
        :return:
        """
        if not vocab_path.endswith('.json'):
            print('vocabulary should be a json file')
            return
        with open(vocab_path, 'w', encoding='utf-8') as f:
            json.dump(self._vocab, f, ensure_ascii=False)

    def _save_labeled_data(self, save_to, description, txt_data):
        if len(txt_data) == 0:
            return
        f = open(save_to, 'w', encoding='utf-8')
        for i in tqdm(range(0, len(txt_data)), desc=description):
            sentence, label = txt_data[i].rsplit(sep=' ', maxsplit=1)
            word_list = self.cut_fn(sentence, stop_words)
            label_idx = self._labels.index(label)
            sentence_idx = [str(self._vocab.get(word, self._vocab['<unk>'])) for word in word_list]
            f.writelines(' '.join(sentence_idx) + '\t' + str(label_idx) + '\n')
        f.close()

    def _save_non_labeled_data(self, save_to, description, txt_data):
        f = open(save_to, 'w', encoding='utf-8')
        for i in tqdm(range(0, len(txt_data)), desc=description):
            word_list = self.cut_fn(txt_data[i], stop_words)
            sentence_idx = list(map(str, [self._vocab.get(word, self._vocab['<unk>']) for word in word_list]))
            f.writelines(' '.join(sentence_idx) + '\n')
        f.close()

    def split_and_save(self, train_idx_path, dev_idx_path=None, frac=0.4):
        """
        将训练数据按比例分为训练集和数据集,并保存为索引
        :param train_idx_path: 训练集索引保存地址
        :param dev_idx_path: 验证集索引保存地址
        :param frac: 训练集和验证集比例
        :return:
        """
        if frac <= 0 or frac > 1:
            print('分割比例必须大于0 且小于等于1')
            return
        if frac < 1 and not dev_idx_path:
            print('分割比例小于1时,必须指定测试集路径')
            return
        if frac == 1 and dev_idx_path:
            print('分割比例等于1时全部数据均用作训练集,测试集路径{}无效'.format(dev_idx_path))

        np.random.shuffle(self._origin_train_data)  # 打乱数据,使每次保存的验证集和测试集均不同
        split_point = int(len(self._origin_train_data) * frac)
        self._save_labeled_data(train_idx_path, 'Saving Train Index', self._origin_train_data[:split_point])
        self._save_labeled_data(dev_idx_path, 'Saving Dev Index', self._origin_train_data[split_point:])

    def save_test_set(self, test_idx_path):
        """
        将测试数据保存为索引
        :param test_idx_path:
        """
        self._save_non_labeled_data(test_idx_path, 'Saving Test Index', self._origin_test_data)


if __name__ == '__main__':
    txt_to_idx = TxtToIndex(
        train_txt_path='data/myTrain.txt',
        test_txt_path='data/myTest.txt',
        cuf_fn=cut_sentence_by_word,
    )
    txt_to_idx.save_test_set('datatest/test_idx.txt')
    txt_to_idx.save_labels('datatest/labels.txt')
    txt_to_idx.save_vocabulary('datatest/vocab.json')
    txt_to_idx.split_and_save('datatest/train_idx.txt', 'datatest/dev_idx.txt', frac=0.6)