Download data_process.py from tobacco/word2vec: direct link, hf CLI and curl.
- Browser
- Download file 6.36 kB
-
https://huggingface.co/datasets/tobacco/word2vec/resolve/main/data_process.py
- Command line
-
hf download hf://datasets/tobacco/word2vec/data_process.py
-
curl -L -o data_process.py https://huggingface.co/datasets/tobacco/word2vec/resolve/main/data_process.py
6.36 kB
| 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) | |