博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 自动化之 第7章从结构化字符串中提取数据之单独对象
阅读量:4144 次
发布时间:2019-05-25

本文共 1020 字,大约阅读时间需要 3 分钟。

1.将第6章内容写成一个对象进行解析

import parse

from decimal import Decimal
import delorean
class PriceLog():
    def __init__(self,timesptamp,product_id,price):
        self.timesptamp = timesptamp
        self.product_id = product_id
        self.price = price
    def __repr__(self):
        return '<PriceLog ({},{},{})>'.format(self.timesptamp,self.product_id,self.price)
    @classmethod
    def parse(cls,text_log):
        '''
        Parse from a text log with the format
        [<Timestamp>] - SALE - PRODUCT: <product_id> -PRICE: $<PRICE> to a PriceLog object
        '''
        divide_id = text_log.split(' - ')
        tmp_string,_,product_string,price_string = divide_id
        timesptamp = delorean.parse(tmp_string.strip('[]'))
        product_id = int(product_string.split(':')[-1])
        price =Decimal(price_string.split('$')[-1])
        return cls(timesptamp=timesptamp,product_id=product_id,price=price)
log = '[2021-02-05T11:07:12.267897] - SALE - PRODUCT: 1345 - PRICE: $09.99'
a = PriceLog.parse(log)
print(a)

 

2.输入log日志值后打印输出结果

<PriceLog (Delorean(datetime=datetime.datetime(2021, 5, 2, 11, 7, 12, 267897), timezone='UTC'),1345,9.99)>

转载地址:http://kcuti.baihongyu.com/

你可能感兴趣的文章
实验9-3 函数的形参为指针变量
查看>>
实验9-4 函数的返回值为指针变量
查看>>
实验9-5 指针变量的运算
查看>>
学习的境界
查看>>
面向对象语言编程的学习视频(类的封装性)
查看>>
C++教学总结
查看>>
win7下安装VC6LineNumberAddin方法[VC6行号插件]
查看>>
计算机的计算
查看>>
第1章 C语言与计算机
查看>>
第2章 基本数据类型
查看>>
第3章 表达式
查看>>
一本支持研究型教学的C语言教材
查看>>
一本支持研究型教学的C语言教材(二)
查看>>
章节导学第4章 逻辑运算与选择结构程序
查看>>
章节导学第5章 循环结构
查看>>
章节导学第6章 数组
查看>>
章节导学第7章 函数
查看>>
章节导学第8章 预处理
查看>>
C语言教材市场的分析
查看>>
章节导学第9章 指针
查看>>