1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
| import re import os import json import pandas as pd from datetime import datetime import glob
class FinancialReportParser: """财务报表解析器""" def __init__(self): self.results = [] def extract_money(self, text: str) -> list: """提取金额""" pattern = r'¥?(\d+(?:,\d{3})*\.?\d*)\s*元?' matches = re.findall(pattern, text) amounts = [] for match in matches: try: clean = match.replace(',', '') amount = float(clean) if amount > 0: amounts.append(amount) except: continue return amounts def extract_dates(self, text: str) -> list: """提取日期""" pattern = r'(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})日?' matches = re.findall(pattern, text) dates = [] for year, month, day in matches: try: date_str = f"{year}-{month.zfill(2)}-{day.zfill(2)}" datetime.strptime(date_str, '%Y-%m-%d') dates.append(date_str) except: continue return dates def extract_invoice_numbers(self, text: str) -> list: """提取发票号""" pattern = r'[A-Z]{2,4}\d{8,12}' return re.findall(pattern, text) def parse_report(self, text: str, filename: str = "") -> dict: """ 解析单份财务报告 输出结构: { '文件': '文件名', '报告日期': '2025-01-26', '公司名称': 'XXX有限公司', '总营收': 2580000.0, '净利润': 450000.0, '主要收入项': [{'名称': 'XX收入', '金额': 1250000.0}, ...], '发票列表': ['INV2025001234', ...] } """ result = { '文件': filename, '报告日期': None, '公司名称': None, '总营收': 0, '净利润': 0, '主要收入项': [], '发票列表': [] } dates = self.extract_dates(text) if dates: result['报告日期'] = dates[0] company_pattern = r'[\u4e00-\u9fa5]+有限公司' company_match = re.search(company_pattern, text) if company_match: result['公司名称'] = company_match.group() revenue_match = re.search(r'营收[^\d]*¥?(\d[,\d]*\.?\d*)', text) if revenue_match: try: result['总营收'] = float(revenue_match.group(1).replace(',', '')) except: pass profit_match = re.search(r'净利润[^\d]*¥?(\d[,\d]*\.?\d*)', text) if profit_match: try: result['净利润'] = float(profit_match.group(1).replace(',', '')) except: pass income_items = re.findall(r'([\u4e00-\u9fa5]+收入)[^\d]*¥?(\d[,\d]*\.?\d*)', text) for name, amount in income_items: try: result['主要收入项'].append({ '名称': name, '金额': float(amount.replace(',', '')) }) except: continue result['发票列表'] = self.extract_invoice_numbers(text) return result def parse_file(self, filepath: str) -> dict: """解析单个文件""" try: print(f"\n📄 处理: {os.path.basename(filepath)}") with open(filepath, 'r', encoding='utf-8') as f: text = f.read() result = self.parse_report(text, os.path.basename(filepath)) result['处理时间'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') return result except Exception as e: print(f"❌ 文件处理失败: {e}") return None def parse_folder(self, folder_path: str) -> pd.DataFrame: """解析文件夹中所有文件""" files = glob.glob(os.path.join(folder_path, "*.txt")) if not files: print("⚠️ 未找到txt文件") return pd.DataFrame() self.results = [] success = 0 for filepath in files: result = self.parse_file(filepath) if result: self.results.append(result) success += 1 print(f"\n✅ 成功处理 {success}/{len(files)} 个文件") if self.results: df = pd.DataFrame(self.results) df['收入项数量'] = df['主要收入项'].apply(len) df['发票数量'] = df['发票列表'].apply(len) return df return pd.DataFrame() def save_to_excel(self, df: pd.DataFrame, output_path: str = None): """保存结果到Excel""" if df.empty: print("⚠️ 无数据可保存") return if output_path is None: output_path = f"财务报表汇总_{datetime.now().strftime('%Y%m%d')}.xlsx" try: with pd.ExcelWriter(output_path, engine='openpyxl') as writer: summary_cols = ['文件', '报告日期', '公司名称', '总营收', '净利润', '收入项数量', '发票数量'] df[summary_cols].to_excel(writer, sheet_name='汇总', index=False) detail_rows = [] for _, row in df.iterrows(): for item in row['主要收入项']: detail_rows.append({ '文件': row['文件'], '报告日期': row['报告日期'], '收入名称': item['名称'], '金额': item['金额'] }) if detail_rows: detail_df = pd.DataFrame(detail_rows) detail_df.to_excel(writer, sheet_name='收入明细', index=False) invoice_rows = [] for _, row in df.iterrows(): for inv in row['发票列表']: invoice_rows.append({ '文件': row['文件'], '报告日期': row['报告日期'], '发票号': inv }) if invoice_rows: inv_df = pd.DataFrame(invoice_rows) inv_df.to_excel(writer, sheet_name='发票清单', index=False) print(f"✅ Excel报告已生成: {output_path}") except Exception as e: print(f"❌ 保存Excel失败: {e}")
def create_sample_data(): """创建示例文件""" os.makedirs("财务报表", exist_ok=True) reports = [ { "filename": "2025-01-财务报告.txt", "content": """ 智慧财务科技有限公司 2025年1月财务报告 报告日期:2025-01-26 本月实现总营收¥2,580,000.00元,净利润¥450,000.00元。 收入构成: 产品销售收入¥1,250,000.00 技术服务收入¥800,000.00 咨询收入¥530,000.00 相关发票:INV2025001234、INV2025001235 """ }, { "filename": "2025-02-财务报告.txt", "content": """ 智慧财务科技有限公司 2025年2月财务报告 报告日期:2025-02-26 本月实现总营收¥3,120,000.00元,净利润¥580,000.00元。 收入构成: 产品销售收入¥1,500,000.00 技术服务收入¥920,000.00 培训收入¥700,000.00 相关发票:INV2025005678 """ }, { "filename": "2025-03-财务报告.txt", "content": """ 智慧财务科技有限公司 2025年3月财务报告 报告日期:2025-03-26 本月实现总营收¥2,950,000.00元,净利润¥520,000.00元。 收入构成: 产品销售收入¥1,400,000.00 技术服务收入¥850,000.00 咨询收入¥700,000.00 相关发票:INV2025009012、INV2025009013、INV2025009014 """ } ] for report in reports: with open(f"财务报表/{report['filename']}", 'w', encoding='utf-8') as f: f.write(report['content']) print("✅ 示例数据已创建在'财务报表'文件夹")
def main(): """主菜单""" parser = FinancialReportParser() print("=" * 55) print("财务报表智能解析器") print("=" * 55) while True: print("\n" + "=" * 45) print("功能菜单") print("=" * 45) print("1. 创建示例数据") print("2. 解析单个文件") print("3. 解析整个文件夹") print("4. 退出") print("=" * 45) choice = input("请选择: ").strip() if choice == "1": create_sample_data() elif choice == "2": filepath = input("文件路径: ").strip() if not os.path.exists(filepath): print("❌ 文件不存在") continue result = parser.parse_file(filepath) if result: print("\n解析结果:") print(json.dumps(result, ensure_ascii=False, indent=2)) elif choice == "3": folder = input("文件夹路径(直接回车用'财务报表'): ").strip() or "财务报表" if not os.path.exists(folder): print("❌ 文件夹不存在") continue df = parser.parse_folder(folder) if not df.empty: print("\n汇总预览:") print(df[['文件', '报告日期', '总营收', '净利润']].to_string()) save = input("\n是否保存为Excel?(y/n): ").strip() if save.lower() == 'y': parser.save_to_excel(df) else: print("⚠️ 没有解析到有效数据") elif choice == "4": print("👋 再见!") break else: print("请输入1-4!")
if __name__ == "__main__": main()
|