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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import string
|
| 2 |
+
import jieba
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import json
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
stop_words = ['!', '……', '?', '的', '了', '嗯', '哦', '啊', '我', '你',
|
| 8 |
+
'她', '他', '它', '在', '和', '吗', '呢', '可以', ',', '。',
|
| 9 |
+
':', ';']
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def cut_sentence_by_word(sentence, stopwords):
|
| 13 |
+
"""
|
| 14 |
+
按照单个字进行分词,需要处理单个英文字
|
| 15 |
+
:param sentence:
|
| 16 |
+
:param stopwords:
|
| 17 |
+
:return:word_list
|
| 18 |
+
"""
|
| 19 |
+
continue_words = string.ascii_lowercase + string.digits
|
| 20 |
+
temp = ""
|
| 21 |
+
result = []
|
| 22 |
+
for word in sentence:
|
| 23 |
+
if word in continue_words:
|
| 24 |
+
temp += word
|
| 25 |
+
continue
|
| 26 |
+
if len(temp) > 0:
|
| 27 |
+
result.append(temp)
|
| 28 |
+
temp = ""
|
| 29 |
+
result.append(word)
|
| 30 |
+
if len(temp) > 0:
|
| 31 |
+
result.append(temp)
|
| 32 |
+
return [word for word in result if word not in stopwords]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def cut_sentence(sentence, stopwords):
|
| 36 |
+
"""
|
| 37 |
+
按照词语进行分词
|
| 38 |
+
:param sentence:
|
| 39 |
+
:param stopwords:
|
| 40 |
+
:return: words_list
|
| 41 |
+
"""
|
| 42 |
+
return [word for word in jieba.lcut(sentence) if word not in stopwords]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def transfer_file_to_list(file_path):
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
:param file_path:
|
| 49 |
+
:return:
|
| 50 |
+
"""
|
| 51 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 52 |
+
lines = [line.rstrip().lower() for line in f]
|
| 53 |
+
return lines
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class TxtToIndex(object):
|
| 57 |
+
def __init__(self, train_txt_path, test_txt_path, cuf_fn):
|
| 58 |
+
"""
|
| 59 |
+
初始化
|
| 60 |
+
:param train_txt_path: 原始训练数据地址
|
| 61 |
+
:param test_txt_path: 原始测试数据地址
|
| 62 |
+
:param cuf_fn: 分割函数,可以按字或者词分割
|
| 63 |
+
"""
|
| 64 |
+
self.cut_fn = cuf_fn
|
| 65 |
+
self._origin_train_data = transfer_file_to_list(train_txt_path)
|
| 66 |
+
self._origin_test_data = transfer_file_to_list(test_txt_path)
|
| 67 |
+
self._labels = []
|
| 68 |
+
self._vocab = {} # {"汀": 0, "哟": 1}
|
| 69 |
+
self._create_vocab_and_labels()
|
| 70 |
+
|
| 71 |
+
def _create_vocab_and_labels(self):
|
| 72 |
+
vocab_length = 0
|
| 73 |
+
label_set = set() # 去重
|
| 74 |
+
for i in tqdm(range(0, len(self._origin_train_data)), desc='Initializing'):
|
| 75 |
+
sentence, label = self._origin_train_data[i].rsplit(sep=' ', maxsplit=1)
|
| 76 |
+
label_set.add(label)
|
| 77 |
+
word_list = self.cut_fn(sentence, stop_words)
|
| 78 |
+
for word in word_list:
|
| 79 |
+
if not self._vocab.get(word):
|
| 80 |
+
self._vocab[word] = vocab_length
|
| 81 |
+
vocab_length += 1
|
| 82 |
+
|
| 83 |
+
self._labels = list(label_set)
|
| 84 |
+
# 异常保护,如果原文中带<unk>或<pad>则用原文中的值
|
| 85 |
+
self._vocab['<unk>'] = vocab_length if not self._vocab.get('<unk>', None) else self._vocab.get('<unk>')
|
| 86 |
+
self._vocab['<pad>'] = vocab_length + 1 if not self._vocab.get('<unk>', None) else self._vocab.get('<unk>')
|
| 87 |
+
|
| 88 |
+
def save_labels(self, label_path):
|
| 89 |
+
"""
|
| 90 |
+
包括所有标签
|
| 91 |
+
:param label_path: 保存地址
|
| 92 |
+
"""
|
| 93 |
+
with open(label_path, 'w', encoding='utf-8') as f:
|
| 94 |
+
for label in self._labels:
|
| 95 |
+
f.writelines(label + '\n')
|
| 96 |
+
|
| 97 |
+
def save_vocabulary(self, vocab_path):
|
| 98 |
+
"""
|
| 99 |
+
包括train和dev的字典
|
| 100 |
+
:param vocab_path: 保存地址
|
| 101 |
+
:return:
|
| 102 |
+
"""
|
| 103 |
+
if not vocab_path.endswith('.json'):
|
| 104 |
+
print('vocabulary should be a json file')
|
| 105 |
+
return
|
| 106 |
+
with open(vocab_path, 'w', encoding='utf-8') as f:
|
| 107 |
+
json.dump(self._vocab, f, ensure_ascii=False)
|
| 108 |
+
|
| 109 |
+
def _save_labeled_data(self, save_to, description, txt_data):
|
| 110 |
+
if len(txt_data) == 0:
|
| 111 |
+
return
|
| 112 |
+
f = open(save_to, 'w', encoding='utf-8')
|
| 113 |
+
for i in tqdm(range(0, len(txt_data)), desc=description):
|
| 114 |
+
sentence, label = txt_data[i].rsplit(sep=' ', maxsplit=1)
|
| 115 |
+
word_list = self.cut_fn(sentence, stop_words)
|
| 116 |
+
label_idx = self._labels.index(label)
|
| 117 |
+
sentence_idx = [str(self._vocab.get(word, self._vocab['<unk>'])) for word in word_list]
|
| 118 |
+
f.writelines(' '.join(sentence_idx) + '\t' + str(label_idx) + '\n')
|
| 119 |
+
f.close()
|
| 120 |
+
|
| 121 |
+
def _save_non_labeled_data(self, save_to, description, txt_data):
|
| 122 |
+
f = open(save_to, 'w', encoding='utf-8')
|
| 123 |
+
for i in tqdm(range(0, len(txt_data)), desc=description):
|
| 124 |
+
word_list = self.cut_fn(txt_data[i], stop_words)
|
| 125 |
+
sentence_idx = list(map(str, [self._vocab.get(word, self._vocab['<unk>']) for word in word_list]))
|
| 126 |
+
f.writelines(' '.join(sentence_idx) + '\n')
|
| 127 |
+
f.close()
|
| 128 |
+
|
| 129 |
+
def split_and_save(self, train_idx_path, dev_idx_path=None, frac=0.4):
|
| 130 |
+
"""
|
| 131 |
+
将训练数据按比例分为训练集和数据集,并保存为索引
|
| 132 |
+
:param train_idx_path: 训练集索引保存地址
|
| 133 |
+
:param dev_idx_path: 验证集索引保存地址
|
| 134 |
+
:param frac: 训练集和验证集比例
|
| 135 |
+
:return:
|
| 136 |
+
"""
|
| 137 |
+
if frac <= 0 or frac > 1:
|
| 138 |
+
print('分割比例必须大于0 ���小于等于1')
|
| 139 |
+
return
|
| 140 |
+
if frac < 1 and not dev_idx_path:
|
| 141 |
+
print('分割比例小于1时,必须指定测试集路径')
|
| 142 |
+
return
|
| 143 |
+
if frac == 1 and dev_idx_path:
|
| 144 |
+
print('分割比例等于1时全部数据均用作训练集,测试集路径{}无效'.format(dev_idx_path))
|
| 145 |
+
|
| 146 |
+
np.random.shuffle(self._origin_train_data) # 打乱数据,使每次保存的验证集和测试集均不同
|
| 147 |
+
split_point = int(len(self._origin_train_data) * frac)
|
| 148 |
+
self._save_labeled_data(train_idx_path, 'Saving Train Index', self._origin_train_data[:split_point])
|
| 149 |
+
self._save_labeled_data(dev_idx_path, 'Saving Dev Index', self._origin_train_data[split_point:])
|
| 150 |
+
|
| 151 |
+
def save_test_set(self, test_idx_path):
|
| 152 |
+
"""
|
| 153 |
+
将测试数据保存为索引
|
| 154 |
+
:param test_idx_path:
|
| 155 |
+
"""
|
| 156 |
+
self._save_non_labeled_data(test_idx_path, 'Saving Test Index', self._origin_test_data)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == '__main__':
|
| 160 |
+
txt_to_idx = TxtToIndex(
|
| 161 |
+
train_txt_path='data/myTrain.txt',
|
| 162 |
+
test_txt_path='data/myTest.txt',
|
| 163 |
+
cuf_fn=cut_sentence_by_word,
|
| 164 |
+
)
|
| 165 |
+
txt_to_idx.save_test_set('datatest/test_idx.txt')
|
| 166 |
+
txt_to_idx.save_labels('datatest/labels.txt')
|
| 167 |
+
txt_to_idx.save_vocabulary('datatest/vocab.json')
|
| 168 |
+
txt_to_idx.split_and_save('datatest/train_idx.txt', 'datatest/dev_idx.txt', frac=0.6)
|