快递成本对比程序,输入重量目的地,对比多家快递价格,选最省钱,时效合适的
快递成本对比程序一、实际应用场景描述在电商蓬勃发展的今天无论是个人寄件还是商家发货都面临着快递选择的难题。同一件包裹不同快递公司的价格可能相差数倍而时效和服务质量也各有差异。比如寄一个3公斤的包裹从北京到上海顺丰可能收费28元次日达圆通可能只要15元隔日达邮政可能12元但需要3-5天。用户往往需要在省钱和时效之间做出权衡。本程序针对这一场景通过Python编程实现智能快递成本对比用户输入包裹重量和目的地后系统自动查询多家快递公司报价综合考虑价格、时效、服务质量等因素推荐最优方案。二、引入痛点1. 信息不对称用户不知道各家快递的真实报价容易被表面的首重优惠误导2. 计算复杂不同快递有不同的计费规则首重续重、分段计价、区域差异3. 时效难预估同样的路线不同时效产品价格差距大难以抉择4. 隐性费用包装费、保险费、偏远地区附加费等容易被忽略5. 服务质量参差不齐便宜的不一定划算丢件率高、破损率高6. 临时决策压力大紧急情况下匆忙选择事后发现多花钱三、核心逻辑讲解3.1 快递比价系统架构┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐│ 用户输入处理 │ → │ 快递公司报价引擎 │ → │ 智能决策分析 ││(重量/目的地/时效)│ │(多源价格获取) │ │(成本效益评估) │└─────────────────┘ └──────────────────┘ └─────────────────┘↓┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐│ 结果展示与推荐 │ ← │ 多维度评分排序 │ ← │ 综合评分计算 ││(最优方案详情) │ │(价格/时效/服务) │ │(加权算法) │└─────────────────┘ └──────────────────┘ └─────────────────┘3.2 核心算法公式快递费用计算模型总费用 首重费用 max(0, 总重量 - 首重) × 续重单价 附加费其中• 首重费用 f(起始地, 目的地, 快递公司)• 续重单价 f(重量区间, 区域类型, 快递公司)• 附加费 包装费 保险费 偏远费 代收货款费智能决策评分算法综合得分 价格得分 × 价格权重 时效得分 × 时效权重 服务得分 × 服务权重价格得分 (最低价 / 当前价) × 100时效得分 (最快时效 / 当前时效) × 100服务得分 服务质量评分基于历史数据约束条件• 时效必须满足用户最低要求• 价格不能超过用户预算上限• 排除服务质量评分过低的选择区域划分算法根据目的地距离划分区域等级• Zone 1同城/近郊0-100km续重单价最低• Zone 2省内/邻省100-500km续重单价中等• Zone 3跨省500-1500km续重单价较高• Zone 4边远地区1500km续重单价最高 偏远附加费四、代码模块化实现4.1 项目结构express_cost_comparator/├── main.py # 程序入口├── config.py # 配置文件├── courier_manager.py # 快递公司管理模块├── pricing_engine.py # 价格计算引擎模块├── decision_engine.py # 智能决策引擎模块├── region_classifier.py # 区域分类模块├── api_client.py # API客户端模块├── cache_manager.py # 缓存管理模块├── utils.py # 工具函数模块├── data/│ ├── couriers.json # 快递公司数据│ ├── pricing_rules.json # 定价规则数据│ └── service_scores.json # 服务质量评分├── logs/│ └── comparison_log.txt # 比价日志├── requirements.txt # 依赖包└── README.md # 项目说明4.2 核心代码实现config.py - 配置文件配置模块 - 存储系统全局配置参数核心知识点配置集中化管理、枚举定义、类型注解from dataclasses import dataclass, fieldfrom typing import Dict, List, Optionalfrom enum import Enumimport osclass ServiceLevel(Enum):服务等级枚举ECONOMY economy # 经济型最便宜时效一般STANDARD standard # 标准型性价比高时效稳定EXPRESS express # 特快型价格较高次日达PREMIUM premium # 尊享型价格最高当日达/专人派送class RegionZone(Enum):区域等级枚举ZONE_1 zone_1 # 同城/近郊 (0-100km)ZONE_2 zone_2 # 省内/邻省 (100-500km)ZONE_3 zone_3 # 跨省 (500-1500km)ZONE_4 zone_4 # 边远地区 (1500km)dataclassclass SystemConfig:系统配置类# API配置api_timeout_seconds: int 10api_retry_times: int 3enable_real_api: bool False # 是否启用真实API默认使用模拟数据# 缓存配置cache_ttl_hours: int 24 # 缓存有效期enable_cache: bool True# 决策权重配置price_weight: float 0.4 # 价格权重time_weight: float 0.35 # 时效权重service_weight: float 0.25 # 服务权重# 过滤配置max_price_threshold: float 500 # 最高价格阈值min_service_score: float 60 # 最低服务质量评分max_delivery_days: int 7 # 最长可接受配送天数dataclassclass CourierBaseInfo:快递公司基础信息code: str # 公司代码name: str # 公司名称website: str # 官网customer_service: str # 客服电话service_levels: List[str] # 支持的服务等级has_insurance: bool # 是否支持保价has_tracking: bool # 是否支持物流跟踪description: str # 公司描述# 快递公司基础数据COURIER_BASE_DATA: Dict[str, CourierBaseInfo] {sf: CourierBaseInfo(codesf,name顺丰速运,websitehttps://www.sf-express.com,customer_service95338,service_levels[ServiceLevel.STANDARD.value, ServiceLevel.EXPRESS.value, ServiceLevel.PREMIUM.value],has_insuranceTrue,has_trackingTrue,description速度快服务好价格相对较高),yt: CourierBaseInfo(codeyt,name圆通速递,websitehttps://www.yto.net.cn,customer_service95554,service_levels[ServiceLevel.ECONOMY.value, ServiceLevel.STANDARD.value, ServiceLevel.EXPRESS.value],has_insuranceTrue,has_trackingTrue,description性价比较高覆盖面广),zt: CourierBaseInfo(codezt,name中通快递,websitehttps://www.zto.com,customer_service95311,service_levels[ServiceLevel.ECONOMY.value, ServiceLevel.STANDARD.value, ServiceLevel.EXPRESS.value],has_insuranceTrue,has_trackingTrue,description价格实惠网络覆盖好),yd: CourierBaseInfo(codeyd,name韵达快递,websitehttps://www.yundaex.com,customer_service95546,service_levels[ServiceLevel.ECONOMY.value, ServiceLevel.STANDARD.value],has_insuranceTrue,has_trackingTrue,description价格较低适合普通物品),st: CourierBaseInfo(codest,name申通快递,websitehttps://www.sto.cn,customer_service95543,service_levels[ServiceLevel.ECONOMY.value, ServiceLevel.STANDARD.value],has_insuranceTrue,has_trackingTrue,description老牌快递网点多),ems: CourierBaseInfo(codeems,name中国邮政EMS,websitehttps://www.ems.com.cn,customer_service11183,service_levels[ServiceLevel.STANDARD.value, ServiceLevel.EXPRESS.value],has_insuranceTrue,has_trackingTrue,description覆盖最广偏远地区首选),jd: CourierBaseInfo(codejd,name京东物流,websitehttps://www.jdl.com,customer_service950616,service_levels[ServiceLevel.STANDARD.value, ServiceLevel.EXPRESS.value, ServiceLevel.PREMIUM.value],has_insuranceTrue,has_trackingTrue,description仓储物流强时效稳定)}# 默认配置DEFAULT_CONFIG SystemConfig()# 数据文件路径DATA_DIR dataLOG_DIR logsCOURIERS_FILE os.path.join(DATA_DIR, couriers.json)PRICING_RULES_FILE os.path.join(DATA_DIR, pricing_rules.json)SERVICE_SCORES_FILE os.path.join(DATA_DIR, service_scores.json)LOG_FILE os.path.join(LOG_DIR, comparison_log.txt)region_classifier.py - 区域分类模块区域分类模块 - 根据地址信息判断区域等级核心知识点地理信息处理、规则引擎、缓存优化import jsonimport osfrom dataclasses import dataclassfrom typing import Dict, Tuple, Optionalfrom enum import Enumimport logginglogging.basicConfig(levellogging.INFO)logger logging.getLogger(__name__)class RegionZone(Enum):区域等级枚举ZONE_1 zone_1 # 同城/近郊 (0-100km)ZONE_2 zone_2 # 省内/邻省 (100-500km)ZONE_3 zone_3 # 跨省 (500-1500km)ZONE_4 zone_4 # 边远地区 (1500km)dataclassclass CityInfo:城市信息类city_name: strprovince: strzone: RegionZonedistance_from_beijing: float # 距北京的公里数用于计算is_remote: bool False # 是否偏远地区class RegionClassifier:区域分类器 - 根据出发地和目的地判断区域等级核心功能地址解析、距离计算、区域判定def __init__(self, cities_data_file: str data/cities_data.json):self.cities_data_file cities_data_fileself.cities_db: Dict[str, CityInfo] {}self._load_cities_data()def _load_cities_data(self) - None:加载城市数据try:if os.path.exists(self.cities_data_file):with open(self.cities_data_file, r, encodingutf-8) as f:data json.load(f)for city_data in data:city_info CityInfo(city_namecity_data[city_name],provincecity_data[province],zoneRegionZone(city_data[zone]),distance_from_beijingcity_data[distance_from_beijing],is_remotecity_data.get(is_remote, False))# 支持城市名和省份名两种keyself.cities_db[city_data[city_name]] city_infoself.cities_db[city_data[province]] city_infoelse:# 使用内置的基础城市数据self._init_default_cities_data()except Exception as e:logger.error(f加载城市数据失败: {e})self._init_default_cities_data()def _init_default_cities_data(self) - None:初始化默认城市数据default_cities [{city_name: 北京, province: 北京, zone: zone_1, distance_from_beijing: 0},{city_name: 上海, province: 上海, zone: zone_3, distance_from_beijing: 1213},{city_name: 广州, province: 广东, zone: zone_3, distance_from_beijing: 2120},{city_name: 深圳, province: 广东, zone: zone_3, distance_from_beijing: 2078},{city_name: 杭州, province: 浙江, zone: zone_3, distance_from_beijing: 1120},{city_name: 南京, province: 江苏, zone: zone_3, distance_from_beijing: 900},{city_name: 天津, province: 天津, zone: zone_1, distance_from_beijing: 120},{city_name: 重庆, province: 重庆, zone: zone_3, distance_from_beijing: 1450},{city_name: 成都, province: 四川, zone: zone_3, distance_from_beijing: 1690},{city_name: 武汉, province: 湖北, zone: zone_3, distance_from_beijing: 1050},{city_name: 西安, province: 陕西, zone: zone_3, distance_from_beijing: 910},{city_name: 沈阳, province: 辽宁, zone: zone_3, distance_from_beijing: 650},{city_name: 哈尔滨, province: 黑龙江, zone: zone_4, distance_from_beijing: 1180, is_remote: True},{city_name: 乌鲁木齐, province: 新疆, zone: zone_4, distance_from_beijing: 2800, is_remote: True},{city_name: 拉萨, province: 西藏, zone: zone_4, distance_from_beijing: 3100, is_remote: True},{city_name: 昆明, province: 云南, zone: zone_4, distance_from_beijing: 2200, is_remote: True},{city_name: 海口, province: 海南, zone: zone_4, distance_from_beijing: 2500, is_remote: True},{city_name: 呼和浩特, province: 内蒙古, zone: zone_3, distance_from_beijing: 400},{city_name: 银川, province: 宁夏, zone: zone_4, distance_from_beijing: 800, is_remote: True},{city_name: 西宁, province: 青海, zone: zone_4, distance_from_beijing: 1400, is_remote: True}]for city_data in default_cities:city_info CityInfo(city_namecity_data[city_name],provincecity_data[province],zoneRegionZone(city_data[zone]),distance_from_beijingcity_data[distance_from_beijing],is_remotecity_data.get(is_remote, False))self.cities_db[city_data[city_name]] city_infoself.cities_db[city_data[province]] city_infologger.info(f已初始化 {len(default_cities)} 个城市数据)def classify_region(self, origin: str, destination: str) - Tuple[RegionZone, RegionZone, float, bool]:对出发地和目的地进行区域分类Args:origin: 出发地destination: 目的地Returns:(出发地区域, 目的地区域, 距离公里数, 是否包含偏远地区)origin_city self._find_city(origin)dest_city self._find_city(destination)if not origin_city:logger.warning(f未找到出发地信息: {origin}使用默认区域)origin_zone RegionZone.ZONE_3origin_distance 500.0else:origin_zone origin_city.zoneorigin_distance origin_city.distance_from_beijingif not dest_city:logger.warning(f未找到目的地信息: {destination}使用默认区域)dest_zone RegionZone.ZONE_3dest_distance 500.0else:dest_zone dest_city.zonedest_distance dest_city.distance_from_beijing# 计算两地之间的距离简化处理使用差值估算distance abs(dest_distance - origin_distance)# 判断是否有偏远地区has_remote (origin_city and origin_city.is_remote) or (dest_city and dest_city.is_remote)# 根据距离重新校准区域等级calculated_zone self._calculate_zone_by_distance(distance)logger.debug(f区域分类结果: 出发地{origin_zone.value}, 目的地{dest_zone.value}, 距离{distance:.0f}km)return origin_zone, dest_zone, distance, has_remotedef _find_city(self, location: str) - Optional[CityInfo]:查找城市信息# 精确匹配if location in self.cities_db:return self.cities_db[location]# 模糊匹配包含关系for city_name, city_info in self.cities_db.items():if location in city_name or city_name in location:return city_info# 省份匹配提取省份名for province in [北京, 上海, 天津, 重庆, 河北, 山西, 辽宁, 吉林, 黑龙江,江苏, 浙江, 安徽, 福建, 江西, 山东, 河南, 湖北, 湖南,广东, 海南, 四川, 贵州, 云南, 陕西, 甘肃, 青海, 台湾,内蒙古, 广西, 西藏, 宁夏, 新疆, 香港, 澳门]:if province in location:if province in self.cities_db:return self.cities_db[province]return Nonedef _calculate_zone_by_distance(self, distance: float) - RegionZone:根据距离计算区域等级if distance 100:return RegionZone.ZONE_1elif distance 500:return RegionZone.ZONE_2elif distance 1500:return RegionZone.ZONE_3else:return RegionZone.ZONE_4def get_shipping_days(self, origin_zone: RegionZone, dest_zone: RegionZone,service_level: str, has_remote: bool False) - int:估算配送天数Args:origin_zone: 出发地区域dest_zone: 目的地区域service_level: 服务等级has_remote: 是否包含偏远地区Returns:预计配送天数# 基础配送时间根据区域跨度zone_diff abs(dest_zone.value.split(_)[1].astype(int) -origin_zone.value.split(_)[1].astype(int))base_days {RegionZone.ZONE_1: 1,RegionZone.ZONE_2: 2,RegionZone.ZONE_3: 3,RegionZone.ZONE_4: 5}# 根据服务等级调整level_multiplier {economy: 1.5,standard: 1.0,express: 0.6,premium: 0.4}multiplier level_multiplier.get(service_level, 1.0)# 偏远地区加时remote_days 2 if has_remote else 0shipping_days int(base_days.get(dest_zone, 3) * multiplier) remote_daysreturn max(1, shipping_days)def add_city(self, city_name: str, province: str, zone: RegionZone,distance_from_beijing: float, is_remote: bool False) - None:添加新城市数据city_info CityInfo(city_namecity_name,provinceprovince,zonezone,distance_from_beijingdistance_from_beijing,is_remoteis_remote)self.cities_db[city_name] city_infoself.cities_db[province] city_infologger.info(f添加城市数据: {city_name}, {province}, {zone.value})pricing_engine.py - 价格计算引擎模块价格计算引擎模块 - 计算各家快递的费用核心知识点计费规则引擎、分段计价、缓存策略import jsonimport osfrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tuplefrom enum import Enumimport mathimport logginglogging.basicConfig(levellogging.INFO)logger logging.getLogger(__name__)class ServiceLevel(Enum):服务等级枚举ECONOMY economySTANDARD standardEXPRESS expressPREMIUM premiumdataclassclass PricingRule:定价规则类courier_code: str # 快递公司代码service_level: str # 服务等级zone: str # 区域等级first_weight: float # 首重kgfirst_weight_price: float # 首重价格元additional_weight: float # 续重单位kgadditional_price: float # 续重价格元/kgmin_charge: float # 最低收费remote_surcharge: float 0 # 偏远地区附加费dataclassclass ShippingCost:运费计算结果courier_code: strcourier_name: strservice_level: strbase_cost: float # 基础运费remote_surcharge: float 0 # 偏远附加费packaging_fee: float 0 # 包装费insurance_fee: float 0 # 保险费total_cost: float # 总费用estimated_days: int # 预计天数class PricingEngine:价格计算引擎 - 根据计费规则计算快递费用核心功能规则匹配、费用计算、附加费处理def __init__(self, pricing_rules_file: str data/pricing_rules.json):self.pricing_rules_file pricing_rules_fileself.rules: Dict[str, List[PricingRule]] {}self.courier_base_info COURIER_BASE_DATAself._load_pricing_rules()def _load_pricing_rules(self) - None:加载定价规则try:if os.path.exists(self.pricing_rules_file):with open(self.pricing_rules_file, r, encodingutf-8) as f:data json.load(f)for rule_data in data:rule PricingRule(courier_coderule_data[courier_code],service_levelrule_data[service_level],zonerule_data[zone],first_weightrule_data[first_weight],first_weight_pricerule_data[first_weight_price],additional_weightrule_data[additional_weight],additional_pricerule_data[additional_price],min_chargerule_data[min_charge],remote_surchargerule_data.get(remote_surcharge, 0))key f{rule.courier_code}_{rule.service_level}if key not in self.rules:self.rules[key] []self.rules[key].append(rule)else:# 使用内置的默认定价规则self._init_default_pricing_rules()except Exception as e:logger.error(f加载定价规则失败: {e})self._init_default_pricing_rules()def _init_default_pricing_rules(self) - None:初始化默认定价规则基于市场调研的模拟数据default_rules [# 顺丰速运{courier_code: sf, service_level: standard, zone: zone_1,first_weight: 1, first_weight_price: 12, additional_weight: 1,additional_price: 2, min_charge: 12, remote_surcharge: 0},{courier_code: sf, service_level: standard, zone: zone_2,first_weight: 1, first_weight_price: 18, additional_weight: 1,additional_price: 5, min_charge: 18, remote_surcharge: 0},{courier_code: sf, service_level: standard, zone: zone_3,first_weight: 1, first_weight_price: 23, additional_weight: 1,additional_price: 8, min_charge: 23, remote_surcharge: 0},{courier_code: sf, service_level: standard, zone: zone_4,first_weight: 1, first_weight_price: 28, additional_weight: 1,利用AI解决实际问题如果你觉得这个工具好用欢迎关注长安牧笛
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2414035.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!