consumables_parser.py
4.04 KB
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
# -*- coding: utf-8 -*-
"""门店资产耗材明细表解析器。
职责:解析「D+门店资产耗材每月采购明细表」(.xls / .xlsx),提取计算门店资产耗材
(store_consumables) 分摊所需的字段:
- 门店名称(对应结果表 traffic_name 的 F 匹配键)
- 系统园区店名称(对应结果表 park_store 的 G 兜底匹配键)
- 业务类型(用于按业务类型分别匹配预算行)
- 月份(用于筛选与 stat_month 对应的当月明细)
- 金额(采购金额,直接作为分摊基数,不做除法)
解析器只负责「读 Excel → 结构化数据」,不关心数据库读写。
支持 .xls(xlrd)与 .xlsx(openpyxl)两种格式,按文件魔数自动识别引擎。
"""
import os
import re
import pandas as pd
# 业务类型后缀(需归一化去掉,使其与预算达成表的 business_type 对齐)
BT_SUFFIXES = ('精品', '权益', '延保', '尊享', '智行')
def _cell(row, col):
"""取单元格并清洗:None / NaN → ''。"""
if col not in row:
return ''
v = row[col]
if v is None or (isinstance(v, float) and pd.isna(v)):
return ''
return v
def _to_num(value):
"""单元格数值归一:None/空/布尔 → 0.0;数字原样;字符串去千分位与货币符号后转 float。"""
if value is None or isinstance(value, bool):
return 0.0
if isinstance(value, (int, float)):
return float(value)
s = str(value).strip().replace(',', '')
if not s:
return 0.0
s = re.sub(r'[^\d.\-]', '', s) # 去掉 ¥、空格等非数字字符
if s in ('', '.', '-'):
return 0.0
try:
return float(s)
except ValueError:
return 0.0
def normalize_bt(s):
"""业务类型归一化:去掉 精品/权益/延保/尊享/智行 等后缀,与预算表 business_type 对齐。"""
s = str(s or '').strip()
for suf in BT_SUFFIXES:
if s.endswith(suf):
s = s[:-len(suf)]
return s
def strip_dplus(name):
"""去掉名称前缀 'D+'(匹配时归一化用)。"""
if name and name.startswith('D+'):
return name[2:]
return name
def _detect_engine(path):
"""按文件魔数识别 Excel 引擎:.xlsx = PK(zip) → openpyxl;.xls = OLE → xlrd。"""
with open(path, 'rb') as f:
head = f.read(8)
if head[:2] == b'PK':
return 'openpyxl'
if head[:4] == b'\xd0\xcf\x11\xe0':
return 'xlrd'
return None
class ConsumablesDetailParser:
"""门店资产耗材明细表解析器。"""
def __init__(self, file_path):
if not os.path.exists(file_path):
raise FileNotFoundError(f'门店资产耗材明细表不存在:{file_path}')
self.file_path = file_path
self.details = []
def parse(self):
"""解析第一个 sheet,返回明细列表。
每行返回 dict:
store_name 门店名称
park_store_name 系统园区店名称
month 月份(如 '6月')
business_type 业务类型(未归一化,如 '1.1精品')
amount 金额(float)
Returns:
list[dict]
"""
engine = _detect_engine(self.file_path)
df = pd.read_excel(self.file_path, engine=engine, header=0, dtype=str)
details = []
for _, row in df.iterrows():
store_name = str(_cell(row, '门店名称')).strip()
park_store = str(_cell(row, '系统园区店名称')).strip()
# 门店名称与系统园区店名称均为空的行视为空行/合计行,跳过
if not store_name and not park_store:
continue
details.append({
'store_name': store_name,
'park_store_name': park_store,
'month': str(_cell(row, '月份')).strip(),
'business_type': str(_cell(row, '业务类型')).strip(),
'amount': _to_num(_cell(row, '金额')),
})
self.details = details
return details