如何用Python从复杂字符串中提取数值范围与费用值?
解决方案:提取公里范围与对应费用并格式化
问题分析
你手里的字符串本质是标准JSON格式,没必要用复杂的字符串替换和正则解析,直接用Python的json模块就能轻松拿到结构化数据,后续导出Excel、做用户分类都会更便捷。
优化后的代码
import json import pandas as pd # 补全原字符串末尾缺失的闭合"}",否则JSON解析会报错 fee_str = '{"row1":{"from":"0","to":"500","fee":"23100 "},"row2":{"from":"500","to":"1000","fee":"24100 "},"row3":{"from":"1000","to":"1500","fee":"25200 "},"row4":{"from":"1500","to":"2000","fee":"26200 "},"row5":{"from":"2000","to":"2500","fee":"27200 "},"row6":{"from":"2500","to":"3000","fee":"28300 "},"row7":{"from":"3000","to":"3500","fee":"29300 "},"row8":{"from":"3500","to":"4000","fee":"30400 "},"row9":{"from":"4000","to":"4500","fee":"31400 "},"row10":{"from":"4500","to":"5000","fee":"32400 "},"row11":{"from":"5000","to":"5500","fee":"33500 "},"row12":{"from":"5500","to":"6000","fee":"34600 "},"row13":{"from":"6000","to":"6500","fee":"35500 "},"row14":{"from":"6500","to":"7000","fee":"36600 "},"row15":{"from":"7000","to":"7500","fee":"37700 "},"row16":{"from":"7500","to":"8000","fee":"38600 "},"row17":{"from":"8000","to":"8500","fee":"39700 "},"row18":{"from":"8500","to":"9000","fee":"40300 "},"row19":{"from":"9000","to":"9500","fee":"41400 "},"row20":{"from":"9500","to":"10000","fee":"42700 "},"row21":{"from":"10000","to":"10500","fee":"43500 "},"row22":{"from":"10500","to":"11000","fee":"44500 "},"row23":{"from":"11000","to":"11500","fee":"45600 "},"row24":{"from":"11500","to":"12000","fee":"46600 "},"row25":{"from":"12000","to":"12500","fee":"47700 "},"row26":{"from":"12500","to":"13000","fee":"48700 "},"row27":{"from":"13000","to":"13500","fee":"49700 "},"row28":{"from":"13500","to":"14000","fee":"50800 "},"row29":{"from":"14000","to":"14500","fee":"51900 "},"row30":{"from":"14500","to":"15000","fee":"52800 "},"row31":{"from":"15000","to":"15500","fee":"52800 "},"row32":{"from":"15500","to":"16000","fee":"52800 "},"row33":{"from":"16000","to":"70000","fee":"52800 "}}' # 解析JSON字符串为字典 data = json.loads(fee_str) # 整理成结构化列表,方便后续处理 fee_list = [] for row_info in data.values(): # 清理费用字段中的特殊空格和空白字符,转换为整数 clean_fee = int(row_info['fee'].replace(' ', '').strip()) fee_list.append({ '起始公里': int(row_info['from']), '结束公里': int(row_info['to']), '费用': clean_fee }) # 直接导出到Excel文件,无需手动处理格式 df = pd.DataFrame(fee_list) df.to_excel('公里费用对照表.xlsx', index=False) # 用于判断用户公里数对应费用的函数 def get_user_fee(user_km): for item in fee_list: # 采用左闭右开逻辑,符合常规区间划分规则 if item['起始公里'] <= user_km < item['结束公里']: return item['费用'] # 超出最大范围时返回最高档费用 return fee_list[-1]['费用'] # 测试分类函数 print(get_user_fee(300)) # 输出:23100 print(get_user_fee(16000)) # 输出:52800
为什么不用原正则方法?
- 原字符串是标准JSON,用
json模块解析更稳定,不会因为字符串格式微小变化(比如空格、特殊字符)导致匹配失败 - 结构化后的列表可直接通过
pandas导出Excel,无需手动拼接格式 - 分类函数逻辑清晰,维护和修改成本更低
关键处理点
- 补全原字符串末尾缺失的
},否则JSON解析会抛出语法错误 - 清理
fee字段中的 和多余空格,确保转换为整数类型时不报错 - 分类函数采用左闭右开的判断逻辑,符合实际场景中区间划分的常规规则
内容的提问来源于stack exchange,提问作者Feiznia
相关产品推荐
相关产品推荐

