You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于TXT文件读取创建产品对象的商店模拟系统实现咨询

解决方案:从TXT文件读取数据创建产品对象

嘿,这个需求我之前做类似的库存系统时也碰到过,咱们一步步来搞定它!

步骤1:分析TXT文件结构

先看你给出的TXT格式,核心结构是:

ΙΤΕΜ_LIST {
ΙΤΕΜ {
ΙΤΕΜ_TYPE monitor
MODEL LS27F350
MODEL_YEAR 2016
MANUFACTURER Samsung
PRICE 220
SCREEN_TYPE LED
DIMENSIONS 27
RESOLUTION ...
}
... 更多ITEM块
}

每个ITEM块对应一个产品,里面包含公共属性(型号、年份、厂商、价格等)和子类特有的属性(比如Monitor的SCREEN_TYPE、DIMENSIONS)。我们要做的就是:提取每个ITEM块→解析键值对→根据ITEM_TYPE实例化对应子类。

步骤2:编写解析逻辑(以Python为例)

假设你已经定义好了Product超类和各个子类,下面是具体的实现思路:

第一步:确保产品类结构正确

class Product:
    def __init__(self, model, model_year, manufacturer, price, stock=0):
        self.model = model
        self.model_year = int(model_year)
        self.manufacturer = manufacturer
        self.price = float(price)
        self.stock = int(stock)

# Monitor子类示例,其他子类(CPU/GPU等)同理
class Monitor(Product):
    def __init__(self, model, model_year, manufacturer, price, screen_type, dimensions, resolution, stock=0):
        super().__init__(model, model_year, manufacturer, price, stock)
        self.screen_type = screen_type
        self.dimensions = int(dimensions)
        self.resolution = resolution

# CPU子类示例
class CPU(Product):
    def __init__(self, model, model_year, manufacturer, price, core_count, clock_speed, stock=0):
        super().__init__(model, model_year, manufacturer, price, stock)
        self.core_count = int(core_count)
        self.clock_speed = float(clock_speed)

第二步:编写文件解析函数

import re

def create_products_from_txt(file_path):
    products = []
    # 读取文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 提取所有ITEM块(非贪婪匹配避免跨块)
    item_blocks = re.findall(r'ITEM { (.*?) }', content, re.DOTALL)
    
    for block in item_blocks:
        attr_dict = {}
        # 逐行解析键值对
        for line in block.strip().split('\n'):
            line = line.strip()
            if not line:
                continue
            # 分割键和值(允许值含空格,仅分割一次)
            key, value = line.split(maxsplit=1)
            attr_dict[key.lower()] = value
        
        # 获取产品类型,跳过无效项
        item_type = attr_dict.get('item_type')
        if not item_type:
            print(f"跳过无效ITEM块:缺少ITEM_TYPE")
            continue
        
        # 提取公共属性
        common_attrs = {
            'model': attr_dict.get('model'),
            'model_year': attr_dict.get('model_year'),
            'manufacturer': attr_dict.get('manufacturer'),
            'price': attr_dict.get('price'),
            'stock': attr_dict.get('stock', '0')  # 库存默认值设为0
        }
        
        # 根据类型实例化对应子类
        try:
            if item_type.lower() == 'monitor':
                product = Monitor(
                    **common_attrs,
                    screen_type=attr_dict.get('screen_type'),
                    dimensions=attr_dict.get('dimensions'),
                    resolution=attr_dict.get('resolution')
                )
                products.append(product)
            elif item_type.lower() == 'cpu':
                product = CPU(
                    **common_attrs,
                    core_count=attr_dict.get('core_count'),
                    clock_speed=attr_dict.get('clock_speed')
                )
                products.append(product)
            # 其他产品类型(Mobo/GPU/Disk等)照此格式添加
            elif item_type.lower() == 'gpu':
                # 替换成你的GPU子类构造逻辑
                pass
            else:
                print(f"暂不支持的产品类型:{item_type}")
        except KeyError as e:
            print(f"创建产品失败,缺少必要属性:{e}")
    
    return products

步骤3:调用函数创建对象

# 替换成你的TXT文件路径
product_list = create_products_from_txt('item_list.txt')

# 验证结果
for p in product_list:
    print(f"产品类型:{type(p).__name__},型号:{p.model},价格:{p.price}")

关键注意事项

  • 数据类型转换:年份、价格、库存等数值型属性要记得转成对应类型(int/float),避免后续计算出错。
  • 缺失属性处理:如果TXT里某些属性可能缺失,可以给默认值,或者抛出异常提醒数据不完整。
  • 编码问题:如果你的TXT文件有特殊编码(比如GBK),要在open函数里指定encoding='gbk'。
  • 正则匹配准确性:如果TXT里的ITEM块格式有变化(比如大括号换行),可能需要调整正则表达式,确保能正确提取每个ITEM。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:40:36