Files
lyxy-document/scripts/utils/encoding_detection.py
lanyuanxiaoyao 9daff73589 refactor: 调整模块导入路径,简化引用结构
- 更新 openspec/config.yaml 中 git 任务相关说明
- 将 scripts.core.* 改为 core.*,scripts.readers.* 改为 readers.*
- 优化 lyxy_document_reader.py 中 sys.path 设置方式
- 同步更新所有测试文件的导入路径
2026-03-09 15:44:51 +08:00

63 lines
1.7 KiB
Python

"""文件编码自动检测模块。"""
from typing import Optional, Tuple
from config import Config
def detect_encoding(file_path: str) -> Tuple[Optional[str], Optional[str]]:
"""
检测文件编码。
Args:
file_path: 文件路径
Returns:
(encoding, error): 成功时返回 (编码名称, None),失败时返回 (None, 错误信息)
"""
try:
import chardet
except ImportError:
return None, "chardet 库未安装"
try:
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
return result['encoding'], None
except Exception as e:
return None, f"编码检测失败: {str(e)}"
def read_text_file(file_path: str) -> Tuple[Optional[str], Optional[str]]:
"""
读取文本文件,自动检测编码。
首先使用 chardet 检测编码,如果失败则尝试配置的回退编码列表。
Args:
file_path: 文件路径
Returns:
(content, error): 成功时返回 (文件内容, None),失败时返回 (None, 错误信息)
"""
# 尝试使用 chardet 检测编码
encoding, error = detect_encoding(file_path)
if error:
# chardet 失败,使用回退编码列表
for enc in Config.FALLBACK_ENCODINGS:
try:
with open(file_path, 'r', encoding=enc) as f:
return f.read(), None
except UnicodeDecodeError:
continue
return None, "无法识别文件编码"
# 使用检测到的编码读取文件
try:
with open(file_path, 'r', encoding=encoding) as f:
return f.read(), None
except Exception as e:
return None, f"读取文件失败: {str(e)}"