# 数据清洗 defclean_text(text): # Windows 换行统一 text = text.replace("\r\n", "\n") text = text.replace("\r", "\n")
# Unicode 规范化 text = unicodedata.normalize("NFKC", text)
# 标点统一 text = text.replace("‘", "'") text = text.replace("’", "'") text = text.replace("“", '"') text = text.replace("”", '"') text = text.replace("—", "--") text = text.replace("…", "...")
# Tab 转空格 text = text.replace("\t", " ")
# 删除控制字符,保留换行 text = "".join( char for char in text if char == "\n"or unicodedata.category(char) != "Cc" )
# 进行每一行的内部清洗 lines = []
for line in text.split("\n"): # 删除首尾空格 line = line.strip()
# 多个连续空格压缩为一个 line = re.sub(r" +", " ", line) lines.append(line)
text = "\n".join(lines)
# 三个及以上换行压缩成两个 text = re.sub(r"\n{3,}", "\n\n", text)
return text
# 将文件读取到 text 内 withopen(file_path, "r", encoding="utf-8") as file: text = file.read()
# 清洗 output_text = clean_text(text)
# 输出文本 withopen(output_Path, "w", encoding="utf-8") as file: file.write(output_text)
print("数据清洗完成")
说明:当前数据清洗方案主要由 AI 辅助生成,我还没有系统学习这一部分。后续会针对文本规范化、异常字符处理和清洗策略继续补充学习。
self.stoi = { character: token_id for token_id, character inenumerate(self.chars) } self.itos = { token_id: character for token_id, character inenumerate(self.chars) }
defencode(self, text: str) -> list[int]: tokens_id = [self.stoi[char] for char in text] return tokens_id
defdecode(self, tokens_id: list[int]) -> str: string = "".join(self.itos[token_id] for token_id in tokens_id) return string