外观
单词转词元id
约 629 字大约 2 分钟
单词转词元id.py
# import urllib.request
# url = ("https://raw.githubusercontent.com/rasbt/LLMs-from-scratch/main/ch02/01_main-chapter-code/the-verdict.txt")
# file_path = "the-verdict.txt"
# urllib.request.urlretrieve(url, file_path)
# 导入正则表达式模块
import re
# 定义第二代简单分词器类
class SimpleTokenizerV2:
# 初始化方法,接收词汇表字典
def __init__(self, vocab):
# 创建字符串到整数的映射字典
self.str_to_int = vocab
# 创建整数到字符串的反向映射字典
self.int_to_str = {i: s for s, i in vocab.items()}
# 编码方法:将文本转换为数字序列
def encode(self, text):
# 使用正则表达式分割文本,保留分隔符作为单独元素
# 正则模式匹配标点符号、特殊符号和空白字符
preprocessed = re.split(r'([,.:;?_!"()\']|--|\s)', text)
# 清理分割后的元素:去除首尾空格,过滤空字符串
preprocessed = [item.strip() for item in preprocessed if item.strip()]
# 处理未知词汇:将不在词汇表的元素替换为<|unk|>
preprocessed = [item if item in self.str_to_int else "<|unk|>" for item in preprocessed]
# 将处理后的每个元素转换为对应的数字标识
ids = [self.str_to_int[s] for s in preprocessed]
return ids
# 解码方法:将数字序列转换回文本
def decode(self, ids):
# 将数字标识转换为对应的字符串,并用空格连接
text = " ".join([self.int_to_str[i] for i in ids])
# 修正标点符号前的多余空格(删除标点前的空格)
# 匹配标点符号前面的一个或多个空格
text = re.sub(r'\s+([,.:;?!"()\'])', r'\1', text)
return text
# -----------------------------------------------------------
# 以下为测试代码部分
# 读取原始文本文件
with open("the-verdict.txt", "r", encoding="utf-8") as f:
raw_text = f.read() # 获取原始文本内容
# 预处理原始文本:分割成基本单元(保留分隔符)
preprocessed = re.split(r'([,.:;?_!"()\']|--|\s)', raw_text)
# 清理分割结果:去除空格,过滤空字符串
preprocessed = [item.strip() for item in preprocessed if item.strip()]
# 构建词汇表
all_words = sorted(set(preprocessed)) # 去重并排序
# 创建初始词汇字典(整数到token的映射)
vocab = {token: integer for integer, token in enumerate(all_words)}
# 扩展特殊标记
all_tokens = sorted(list(set(preprocessed))) # 再次去重排序
all_tokens.extend(["<|endoftext|>", "<|unk|>"]) # 添加文本结束标记和未知词标记
# 重建词汇字典(包含特殊标记)
vocab = {token: integer for integer, token in enumerate(all_tokens)}
# 构造测试文本
text1 = "Hello, do you like tea?" # 测试句子1
text2 = "In the sunlit terraces of the palace." # 测试句子2
# 使用特殊标记连接两个句子
text = " <|endoftext|> ".join((text1, text2))
# 实例化分词器
tokenizer = SimpleTokenizerV2(vocab)
# 打印编码后的数字序列
print(tokenizer.encode(text))
# 解码并打印重构的文本(展示可逆性)
print(tokenizer.decode(tokenizer.encode(text)))
更新日志
2025/6/26 11:30
查看所有更新日志
dfb81
-update于dc6b2
-update于
版权所有
版权归属:NateHHX