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

从字符串提取Decimal类型值:读取文本文件的类型转换问题

解决方案

要解决Decimal类型被解析为双重字符串的问题,核心是识别文本中的Decimal('xxx')格式字符串,将其转换为实际的Decimal对象,而非保留字符串格式。具体实现如下:

修改后的完整代码

from decimal import Decimal

damages = []
def parse(d):
    dictionary = dict()
    # 移除大括号并分割键值对
    pairs = d.strip('{}').split(', ')
    for i in pairs:
        pair = i.split(': ')
        # 清理键的外层引号
        key = pair[0].strip('\'"')
        # 清理值的外层引号
        value_str = pair[1].strip('\'"')
        
        # 判断是否为Decimal格式的字符串
        if value_str.startswith('Decimal(') and value_str.endswith(')'):
            # 提取内部的数值字符串并转换为Decimal对象
            num_str = value_str[8:-1].strip('\'')
            dictionary[key] = Decimal(num_str)
        else:
            # 处理普通数字,优先转整数,否则转Decimal
            try:
                dictionary[key] = int(value_str)
            except ValueError:
                dictionary[key] = Decimal(value_str)
    return dictionary

try:
    with open('TowerA/0-deg-DamagesStates.txt', 'rt') as geeky_file:
        lines = geeky_file.read().split('\n')
        for l in lines:
            if l.strip():  # 过滤空行(包括仅含空格的行)
                dictionary = parse(l)
                damages.append(dictionary)
except Exception as e:
    print(f"发生意外错误: {e}")

关键修改说明

  • 导入Decimal类:必须先导入decimal模块的Decimal类,才能创建实际的Decimal对象。
  • 简化引号清理:用strip('\'"')替代原代码中复杂的引号组合,能高效清理所有外层的单双引号。
  • Decimal格式转换:通过字符串首尾匹配识别Decimal(格式,提取内部数值字符串后转换为Decimal对象。
  • 普通数字兼容:对非Decimal格式的数字字符串,先尝试转整数,失败则转Decimal,保证数值类型统一。
  • 优化文件操作:改用with语句自动管理文件关闭,避免手动关闭遗漏;同时过滤空行,避免无效数据解析。
  • 错误信息优化:捕获具体异常并打印详情,方便排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:52:37