清理文本中的特殊字符,确保可以安全输出
(text: str)
| 75 | ) |
| 76 | |
| 77 | def clean_text(text: str) -> str: |
| 78 | """清理文本中的特殊字符,确保可以安全输出""" |
| 79 | if not text: |
| 80 | return "" |
| 81 | |
| 82 | # 移除或替换问题字符 |
| 83 | text = text.replace('\ufffd', '?') # 替换替换字符 |
| 84 | text = text.replace('\x00', '') # 移除空字符 |
| 85 | |
| 86 | # 确保可以编码为当前系统编码 |
| 87 | try: |
| 88 | # 先尝试编码为 UTF-8 |
| 89 | text.encode('utf-8') |
| 90 | return text |
| 91 | except UnicodeEncodeError: |
| 92 | # 如果失败,使用替换策略 |
| 93 | return text.encode('utf-8', errors='replace').decode('utf-8') |
| 94 | |
| 95 | class BuildError(Exception): |
| 96 | """Custom exception for build errors""" |