You need to enable JavaScript to run this app. 如何优化通过ASIN匹配双JSON行文件查询商品信息的代码
优惠活动
大模型
产品
解决方案
定价
更多

如何优化通过ASIN匹配双JSON行文件查询商品信息的代码

代码优化方案

核心优化逻辑

你当前的双层for循环时间复杂度为O(M*N)(M为评论文件行数,N为元数据文件行数),数据量较大时性能会非常差。最优方案是提前将商品元数据处理为以ASIN为键的哈希字典,单次查询复杂度降到O(1),整体时间复杂度直接降到O(M+N),性能提升非常明显。

额外可优化点

  • 原代码用tempArr列表判断ASIN是否重复,in操作复杂度为O(n),替换为set集合后复杂度降到O(1)
  • 原代码直接对JSON格式的评论行执行split(',')取ASIN逻辑错误:如果评论内容里包含逗号,会直接拿错字段,必须用JSON解析工具读取字段
  • 移除不必要的全局变量声明,避免全局命名空间污染,用函数返回值传递结果即可
  • with上下文管理器会自动关闭文件,不需要手动调用y.close()
  • 增加异常处理逻辑,避免价格正则匹配失败、JSON解析失败等场景导致程序崩溃

优化后代码示例

import json
import re
from collections import defaultdict

def get_ecoList(category1, metaCat):
    # 第一步:预处理元数据为ASIN映射字典,只处理一次
    meta_map = {}
    meta_list = read_metadata(metaCat)
    for item in meta_list:
        if 'asin' not in item:
            continue
        asin = item['asin']
        # 提前处理价格和描述,避免查询时重复处理
        price = '$1.0'
        if 'price' in item and len(item['price'].strip()) > 0:
            price = item['price']
        desc = 'N/A'
        if 'description' in item:
            desc_list = item['description']
            if len(desc_list) > 1:
                desc = ''.join(desc_list)
            elif len(desc_list) == 1:
                desc = desc_list[0]
        meta_map[asin] = {
            'price': price,
            'description': desc
        }
    
    ecoList = []
    prices = []
    processed_asins = set()
    # 第二步:遍历评论文件,直接查表
    with open(category1, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            # 正确解析JSON格式的评论行
            try:
                review = json.loads(line)
            except json.JSONDecodeError:
                continue
            asin = review.get('asin')
            if not asin or asin in processed_asins:
                continue
            processed_asins.add(asin)
            # 直接查表,不需要遍历元数据
            meta_info = meta_map.get(asin, {})
            # 处理价格
            raw_price = meta_info.get('price', '$1.0')
            try:
                price_num = float(re.findall(r"\d+\.\d+", raw_price)[0])
                prices.append(price_num)
            except (IndexError, ValueError):
                prices.append(1.0)
            # 处理描述
            ecoList.append(meta_info.get('description', 'N/A'))
    return ecoList, prices

内容的提问来源于stack exchange,提问作者javaMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 17:15:05