用正则获取txt订单数据并写入excel表

本文介绍如何利用正则表达式从TXT文件中提取订单信息,并将这些数据有效地整理到Excel表格中,以实现快速的数据管理和分析。
摘要由CSDN通过智能技术生成
import re
import xlwt

#order_info=[{"81502804":[{"38":{"#03":80,"#11":40,"#30":45,"#50":65,"#70":55,"#76":45}}]},
    #{"81502805":[{"38":{"#76":35,"#32":35,"#60":35}}]}] # 模板

class ProcessTxtOrder(object): 

    def __init__(self,txt_path,write_path):
        self.txt_path=txt_path
        self.write_path=write_path
        
    def read_txt(self):
        try:
            f=open(self.txt_path,"r")
            self.content_line=f.readlines()
            f.close()
        except Exception as ret:
            print(ret)
            
    def handle_content_line(self):
        self.new_order=[]
        for i in self.content_line:
            size=re.findall(r"4[0246]{1}\s4[0246]{1}\sFREE\s",i) 
            style=re.findall(r"(C[VHPL]{1}-[0-9]{8})",i)
            col=re.findall(r"([0-9]{2}\))",i)
            if style!=[] or col!=[]or size!=[]:
                if size!=[]:
                    self.new_order.append(size[0])
                elif style!=[]:
                    self.new_order.append(style[0])
                    if col!=[]:
                        self.new_order.append(col[0])
                        quantity=re.findall(r'[0-9]+\)\s([0-9]+|\s|-)\s([0-9]+|\s|-)',i)
                        if quantity!=[]:
                            self.new_order.append(quantity[0])
                            #print("type of quantity:",type(quantity[0]))
                            #print(quantity)
                elif col!=[]:
                        self.new_order.append(col[0])
                        quantity=re.findall(r'[0-9]+\)\s([0-9]+|\s|-)\s([0-9]+|\s|-)',i)
                        if quantity!=[]:
                            self.new_order.append(quantity[0])
                            #print("type of quantity:",type(quantity[0]))
                            #print(quantity) 
                else:
                    print("出错了")
        return  self.new_order  
        
    def write_processed_result(self):
        try:
            f=open(self.write_path,"w")
            f.write(str(self.new_order))
            f.close()
        except Exception as ret:
            print(ret) 
           
    def run(self):
        self.read_txt()
        self.handle_content_line()
        self.write_processed_result()
        
class MakeListDictNestedFormat(object):

    def __init__(self,order_list):
        self.order_list=order_list
        
    def transform_order_list_into_nested_format(self):
        self.general_list=[]
        dict_col={}
        i=0
        while i<len(self.order_list):       
            if type(self.order_list[i])!=tuple:
                size=re.match(r"(4[0246]{1})\s(4[0246]{1})\s(F)REE\s",self.order_list[i])
                style=re.match(r"(C[VHPL]{1}-[0-9]{8})",self.order_list[i])
                col=re.match(r"^([0-9]{2})\)$",self.order_list[i])
                if size!=None:
                    order_size_list=[size.group(1),size.group(2),size.group(3)]
                    #order_size=[]
                if style!=None:  
                    if dict_col!={}:
                        search_none=[]
                        for key in dict_col:
                            if dict_col[key]=={}:
                                search_none.append(key)
                        if len(search_none)!=0:
                            for y in search_none:
                                del dict_col[y]
                        dict_style[order_style].append(dict_col)
                        self.general_list.append(dict_style)
                        #print(dict_style)
                        dict_col={}
                    dict_style={}
                    #print(dict_style)
                    order_style=style.group(1)
                    dict_style[order_style]=[]
                    for size in order_size_list:
                        dict_col[size]={}  
                    is_f_size=False           
                if col!=None:
                    order_color="#"+col.group(1)           
            elif type(self.order_list[i])==tuple:
                #print(order_size_list,order_style,order_color)
                if self.order_list[i][1]=='\n': #判断是否是F码
                    #order_size=order_size_list[2]           
                    is_f_size=True
                # else:
                    # pass
                    #dict_col[order_size_list[2]]={}
                if is_f_size==False :
                    #print(order_list[i])
                   
                    #print('is_f_size==False CL-31980105 尺寸:',order_size_list)
                    if order_size_list[2] in dict_col:
                        del dict_col[order_size_list[2]]
                    x=0
                    while x<len(self.order_list[i]):
                        if self.order_list[i][x].isdigit()==True:
                            #dict_col[order_size_list[x]]={}
                            dict_col[order_size_list[x]][order_color]=int(self.order_list[i][x])
                        x+=1        
                        #dict_col[order_size_list[2]]={}
                elif is_f_size==True:
                   
                    #print('is_f_size==True',order_size_list)
                    if order_size_list[0]in dict_col:
                        del dict_col[order_size_list[0]]
                    if order_size_list[1]in dict_col: 
                        del dict_col[order_size_list[1]]
                    if self.order_list[i][0].isdigit()==True:
                        dict_col[order_size_list[2]][order_color]=int(self.order_list[i][0])           
            i+=1
        self.add_final_style_into_general_list(dict_col,order_style,dict_style)
        
    def add_final_style_into_general_list(self,dict_col,order_style,dict_style):
        #把最后一个款号数据添加到总列表中
        if dict_col!={}:
            search_none=[]
            for key in dict_col:
                if dict_col[key]=={}:
                    search_none.append(key)
            if len(search_none)!=0:
                for y in search_none:
                    del dict_col[y]
            dict_style[order_style].append(dict_col)
            self.general_list.append(dict_style)
            return self.general_list
        #print(general_list)
    
        
class PrintOrderTips(object):

    def __init__(self,sheet_name,workbook_path_name,order_info):        
        self.workbook_path_name=workbook_path_name #获取存储路径
        self.sheet_name=sheet_name #获取表名
        self.workbook = xlwt.Workbook()#创建WORKBOOK对象
        self.borders=xlwt.Borders()#创建边框对象
        self.style=xlwt.XFStyle() #创建表格风格对象
        self.style_jione=xlwt.XFStyle()
        self.style_size_col=xlwt.XFStyle()
        self.alignment = xlwt.Alignment()
         # 0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)
        self.alignment.horz = 0x02
        # 0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)
        self.alignment.vert = 0x01       
        self.worksheet = self.workbook.add_sheet(self.sheet_name)#创建名为self.sheet_name表单
        self.order_info=order_info #传入订单信息
        self.count=0 #设置初始计数器为0
        self.old_count=0 #设置上一步计数器为0
        self.speed=7 #定义每7行打印一次        
    # def set_sheet_style(self):                               
        # #borders=xlwt.Borders()
        self.borders.left=xlwt.Borders.THIN #设置左边框为Thin
        self.borders.right=xlwt.Borders.THIN#设置右边框为Thin
        self.borders.top=xlwt.Borders.THIN#设置上边框为Thin
        self.borders.bottom=xlwt.Borders.THIN# 设置下边框为Thin
        self.borders.left_colour=0x0 #设置左边框颜色为黑色
        self.borders.right_colour=0x0#设置右边框颜色为黑色
        self.borders.top_colour=0x0#设置上边框颜色为黑色
        self.borders.bottom_colour=0x0  #设置下边框颜色为黑色      
        self.style.borders=self.borders #将设置好的边框风格赋给style.borders对象
        self.style_jione.alignment=self.alignment#将设置好的对齐风格赋给style.borders对象
        self.style_jione.borders=self.borders#将设置好的边框风格赋给style_jione.borders对象
        self.style_size_col.alignment=self.alignment
        self.style_size_col.borders=self.borders
        
    def process_orderinfo(self):
        for x in range(len(self.order_info)):#遍历订单找出所有的款号
            style_garment=[key for key in self.order_info[x].keys()][0]
            #print("style:",style_garment)
            for y in range(len(self.order_info[x][style_garment])):#遍历订单找出所有的尺码
                size=[key for key in self.order_info[x][style_garment][y].keys()][0]
                #print("size:",size)       
                for key in self.order_info[x][style_garment][y][size].keys(): #遍历订单找出每款每色对应的数量          
                    color_garment=key
                    #print("color",color_garment)
                    quantity_size_color=int((self.order_info[x][style_garment][y][size][color_garment])*1.2/3+1)
                    #print("quantity",quantity_size_color)
                    self.count+=quantity_size_color
                    #new_count=count*speed
                    #print("count",self.count)
                    self.construct_sheet(size,style_garment,color_garment)#将尺码,颜色,款号传给construct_sheet用于建造表格
                    
    def construct_sheet(self,size,style_garment,color_garment):
        for l in range(self.old_count,self.count):#小纸条行数
            for i in range(6):
                self.worksheet.col(i).width = 256 * 15# 设置表格的宽度
                if i==0 or i%2==0:
                    self.worksheet.write((0+l*self.speed), i, '',self.style) 
                    self.worksheet.write((1+l*self.speed), i, 'CODE NO:',self.style)
                    self.worksheet.write((2+l*self.speed), i, 'COL.NO:',self.style)
                    self.worksheet.write((3+l*self.speed), i, 'SIZE:',self.style)           
                    self.worksheet.write((4+l*self.speed), i, '',self.style)
                    self.worksheet.write_merge((5+l*self.speed),(5+l*self.speed), i,i+1, 'JIONE CO.,LTD',self.style_jione)#合并单元格
                    self.worksheet.write((6+l*self.speed), i, '',self.style)
                    #worksheet.write((5+l*speed), i, ' ',style)
                    self.worksheet.write((0+l*self.speed), i+1, '',self.style)
                    self.worksheet.write((1+l*self.speed), i+1, style_garment,self.style_size_col)
                    self.worksheet.write((2+l*self.speed), i+1, color_garment,self.style_size_col)
                    self.worksheet.write((3+l*self.speed), i+1, size,self.style_size_col)
                    self.worksheet.write((4+l*self.speed), i+1, '',self.style)
                    self.worksheet.write((6+l*self.speed), i+1, '',self.style)
        self.old_count=self.count     
        
    def save_excel(self):
        workbook.save( self.workbook_path_name)
        
    def run(self):
        self.process_orderinfo()
        self.workbook.save( self.workbook_path_name)   
 
def main():
    read_path=r"D:\EXCEL TEST\Q303R-1&Q304R-1&Q305R-1&Q306R-1.txt"
    #获取txt订单位置
    write_path=r"D:\EXCEL TEST\abustract_test.txt"
    #获取订单列表的写入路径
    sheet_name="sheet01" 
    #设置表名
    workbook_path_name="D:\EXCEL TEST\测试01.xls"
    #设置excel文件名
    # read_path=input('请输入txt订单路径')
    # write_path=input("请输入订单列表的写入路径")
    # workbook_path_name=input("请输入excel表写入路径")
    # sheet_name= input("请输入excel的表名")
        
    #1.获取txt订单信息列表
    pto=ProcessTxtOrder(read_path,write_path)
    pto.run()
    order_list=pto.new_order
    #2.获取字典列表的嵌套订单
    mdnf=MakeListDictNestedFormat(order_list)
    mdnf.transform_order_list_into_nested_format()
    nested_order=mdnf.general_list
    #3.打印小纸条    
    make_sheet=PrintOrderTips(sheet_name,workbook_path_name,nested_order)
    make_sheet.run()
    print("打印完成。。")
    
if __name__=="__main__":
    
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值