get_whole_number函数参数异常:应接收字符串却传入对象
问题排查与修复方案
一、get_whole_number函数参数类型错误及修复
问题根源
- 函数参数名使用Python内置类型
str,易引发命名冲突;调用时传入的可能是pandas单元格对象(如pd.Series元素)而非字符串。 - 函数内引用未定义的正则变量
WHOLE_NUMBER_PATTERN,实际常量定义为CSI_NUMBER_PATTERN,运行时会抛出NameError。 - 未对传入参数做类型转换,直接调用字符串方法,若参数为非字符串对象(如NaN、数值类型)会触发属性错误。
修复代码
# 重命名参数避免冲突,先转字符串处理,修正正则变量名 def get_whole_number(s): s_str = str(s) if s is not None else "" if s_str.strip() == "": return "" match = CSI_NUMBER_PATTERN.match(s_str) return match.group().strip() if match else ""
二、Excel转CSV未生效的问题及修复
代码存在多处逻辑错误和语法问题,导致无法生成有效CSV,具体问题及修复如下:
1. 函数参数不匹配
process_excel_file_as_pd中调用generate_csv_row时传入5个参数,但该函数仅定义3个参数,参数数量不匹配会直接报错终止流程。需调整参数传递,保证数量与定义一致。
2. 循环逻辑错误
process_excel_file_as_pd的while循环中,第一次迭代就执行return output_rows,导致仅处理一行数据就返回,无法遍历所有行。需将return output_rows移到循环外部。
3. 变量赋值与判断逻辑错误
Ven_div = [('Vendor: AI','Unnamed: 10_level_1 ')]是列表类型,与空字符串''比较永远为True,正确写法应为从row中提取对应单元格值:Ven_div = row.get(('Vendor: AI','Unnamed: 10_level_1 '), '')- 对
FMS调用startswith和直接字符串比较前,未判断是否为字符串类型,若FMS是NaN或数值,会触发属性错误,需先转字符串再判断。
4. 未实现CSV写入逻辑
代码仅生成output_rows列表,但无写入CSV文件的逻辑,需添加文件写入代码。
5. generate_csv_row函数逻辑问题
将整个row_data(pandas Series)加入csv_row会导致CSV内容混乱,应提取需要的字段而非整个对象。
修复后的核心代码片段
def generate_csv_row(FMS_ID, project_name, vendor_total): # 仅保留需要的字段,避免写入复杂对象 return (FMS_ID, project_name, vendor_total) def process_excel_file_as_pd(data, FMS_ID, project_name): output_rows = [] current_Fms_Id = None current_Vendor_Total = None i = 1 while i < len(data): row = data.iloc[i] # 转字符串避免属性错误 FMS = str(row.get(('FMS ID \n Capital Projects', 'Unnamed: 1_level_1'), '')) # 正确提取Vendor值 Ven_div = row.get(('Vendor: AI','Unnamed: 10_level_1 '), '') if FMS.startswith('FMS ID'): current_Fms_Id = FMS i += 1 continue # 判断Ven_div是否非空 if Ven_div.strip() != '': current_Vendor_Total = Ven_div if FMS == 'copy above cell and insert copied cell above the row': if current_Fms_Id is not None and current_Fms_Id.startswith('PVO28-ISS'): break current_Fms_Id = None current_Vendor_Total = None i += 2 continue # 跳过后续处理,直接进入下一次循环 # 调用时参数数量匹配 if current_Vendor_Total is not None: csv_row = generate_csv_row(FMS_ID, project_name, current_Vendor_Total) output_rows.append(csv_row) i += 1 # 将结果写入CSV文件 with open('output.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) # 写入表头 writer.writerow(['FMS ID', 'Project Name', 'Vendor Total']) writer.writerows(output_rows) return output_rows
内容的提问来源于stack exchange,提问作者Arvin Azad
相关产品推荐
相关产品推荐

