导出词表到文件
(tokenizer, file_path: str)
| 153 | |
| 154 | |
| 155 | def export_vocabulary(tokenizer, file_path: str) -> None: |
| 156 | """导出词表到文件""" |
| 157 | try: |
| 158 | vocab = get_vocab_dict(tokenizer) |
| 159 | if not vocab: |
| 160 | print("Warning: Could not retrieve vocabulary from tokenizer") |
| 161 | return |
| 162 | |
| 163 | path = Path(file_path) |
| 164 | path.parent.mkdir(parents=True, exist_ok=True) |
| 165 | |
| 166 | # 根据文件扩展名选择格式 |
| 167 | if path.suffix.lower() == ".json": |
| 168 | with open(path, "w", encoding="utf-8") as f: |
| 169 | json.dump(vocab, f, ensure_ascii=False, indent=2) |
| 170 | else: |
| 171 | # 默认格式:每行一个token |
| 172 | with open(path, "w", encoding="utf-8") as f: |
| 173 | for token, token_id in sorted(vocab.items(), key=lambda x: x[1]): |
| 174 | # 处理不可打印字符 |
| 175 | try: |
| 176 | f.write(f"{token_id}\t{repr(token)}\n") |
| 177 | except: |
| 178 | f.write(f"{token_id}\t<unprintable>\n") |
| 179 | |
| 180 | print(f"Vocabulary exported to: {file_path}") |
| 181 | print(f"Total tokens: {len(vocab)}") |
| 182 | |
| 183 | except Exception as e: |
| 184 | print(f"Error exporting vocabulary: {e}") |
| 185 | |
| 186 | |
| 187 | def main(args: argparse.Namespace) -> None: |