""" TXT 文本解析器 简单的文本文件读取,支持 UTF-8 和 GBK 编码自动检测。 """ import logging import os logger = logging.getLogger(__name__) # 文件大小限制 MAX_TXT_SIZE = 20 * 1024 * 1024 # 20MB def extract_text_from_txt(filepath): """从TXT提取文本""" # 检查文件大小 try: file_size = os.path.getsize(filepath) if file_size > MAX_TXT_SIZE: logger.error(f"TXT文件过大: {file_size / 1024 / 1024:.1f}MB") return "" except OSError: return "" try: with open(filepath, 'r', encoding='utf-8') as f: return f.read() except UnicodeDecodeError: # 尝试其他编码 try: with open(filepath, 'r', encoding='gbk') as f: return f.read() except Exception as e: logger.error(f"TXT解析错误 {filepath}: {e}") return "" except Exception as e: print(f" TXT解析错误 {filepath}: {e}") return ""