zoukankan      html  css  js  c++  java
  • Python_Example_ 读取excel数据 进行匹配识别

     Author: 楚格

    2018-11-14  21:11:04

    IDE: Pycharm2018.02   Python 3.7   

    KeyWord :  面向对象实例

    Explain:  

    1.path读取路径

    2.API获取数据以及处理

    3.思路

    3.1先获取路径,包括动态获取当前路径,可视化选择文件,简单防止误操作判断。

    3.2先获取Excel中数据,固定行列位置,读取的数据存储在列表中,列表中的元素以字典方式存储,便于查找。

    3.3 读取standard和actual数据,以actual的一列中的某个数据与standard的一列数据进行对比,判断。

    3.4若对比结束,返回信息。包括屏幕打印和日志保存的统计信息。

    3.5正则表达,判断首字母是新增的

    3.6此部分程序可以作为模块接口示例程序。

    -----------------------------------------------------------------------------

    程序结构图

    --------------------------------------------------------------------------------

    path

    -------

      1 # coding=utf-8
      2 #---------------------------------
      3 '''
      4 # Author  : chu ge 
      5 # Function: 提取文件路径
      6 #
      7 '''
      8 #---------------------------------
      9 __all__ = ['Class_File_Read']
     10 
     11 import os
     12 
     13 '''
     14 # ============================================================================
     15 # Class   :    类   file  path
     16 # Explain :  输入参数   文件的序号
     17 #         :  输出参数  global_var_file_name_file <路径>
     18 # ============================================================================
     19 '''
     20 class Class_File_Read(object):
     21     def __init__(self):
     22         # print('Class file read excel')
     23         self.Methoons_File_Directory()
     24 
     25     def Methods_File_Operation_Standard(self):
     26         print('
    standard input:0 ')
     27         STANDARD = "0"
     28         File_Path = self.Methods_Select_File(STANDARD)
     29         print("Methods_File_Operation_Standard 
    ")
     30         return File_Path
     31 
     32     def Methods_File_Operation_Actual(self):
     33         number = input("Actual Input :")
     34         # number = "1" # 临时
     35         File_Path = self.Methods_Select_File(number)
     36         print("Methods_File_Operation_Actual 
    ")
     37         return File_Path
     38 
     39     def Methoons_File_Directory(self):
     40         # 初始化列表 存放文件
     41         local_var_num = []
     42         local_var_file_name = []
     43         # 获取当前文件路径 调试使用
     44         # local_var_cwd = os.getcwd()
     45         # print('当前文件夹的路径  :
    ->>>  < %s >' % local_var_cwd )
     46         # [dir_name, file_name] = os.path.split(local_var_cwd)
     47         # print('分离files & path:< %s >     < %s >'%(dir_name,file_name))
     48         # 固定文件夹目录
     49         try:
     50             local_var_cwd = 'D:Auto_Testing_PycharmTest_InstanceTest_User_Excelexcel'
     51             local_var_list_name = os.listdir(local_var_cwd)  # # print('当前文件夹下的所有文件和文件夹:')
     52         except Exception:
     53             print("捕获异常:
    目录:<%s>
    位置:<%s>"%(os.getcwd(),"固定文件夹目录"))
     54 
     55 
     56         # 遍历文件夹 编号 +  文件名
     57         for temp_var_num in range(len(local_var_list_name)):
     58             # print('num:%s   name:< %s >'% (temp_var_num,local_var_list_name[temp_var_num]))    # display All
     59             [new_file_name, file_name_end] = os.path.splitext(local_var_list_name[temp_var_num])  # file name handle
     60             # print('分离文件名与后缀:< %s >   < %s > '%(new_file_name,file_name_end))              # display result
     61 
     62             # 过滤其他文件 保留Excel文件 以供选择
     63             if file_name_end == '.xlsx':
     64                 local_var_num.append(temp_var_num)  # 存储文件编号
     65                 local_var_file_name.append(local_var_list_name[temp_var_num])  # 存储文件名称
     66                 # print('Display select files : ', local_var_num, local_var_file_name)  # 显示二个列表
     67             # ------------------------------------------------------------------------------------------
     68             # 显示留存的文件  二个列表映射成字典 保留列表方便调试使用  技巧 ***
     69         local_var_storage = dict(zip(local_var_num, local_var_file_name))
     70 
     71         #  提示 遍历字典元素 显示内容 local_var_storage.items() 无序
     72         #  可以这个替换 : print('Your selecr pprotocol : < %s > '% local_var_storage.keys())
     73         # print('Protocols that can be executed :  ')
     74         for temp_var_num in local_var_storage:
     75             print("", temp_var_num, local_var_storage[temp_var_num])
     76         # -----------------------------------------------------------------------------
     77 
     78     def Methods_Select_File(self,number):
     79         global  global_var_file_name_file
     80         local_var_select_number = number
     81 
     82         # 固定文件夹目录
     83         local_var_cwd = 'D:Auto_Testing_PycharmTest_InstanceTest_User_Excelexcel'
     84         local_var_list_name = os.listdir(local_var_cwd)  # # print('当前文件夹下的所有文件和文件夹:')
     85         local_var_num = []
     86         local_var_file_name = []
     87 
     88         for temp_var_num in range(len(local_var_list_name)):
     89             [new_file_name, file_name_end] = os.path.splitext(local_var_list_name[temp_var_num])  # file name handle
     90             if file_name_end == '.xlsx':
     91                 local_var_num.append(temp_var_num)                                      # 存储文件编号
     92                 local_var_file_name.append(local_var_list_name[temp_var_num])           # 存储文件名称
     93 
     94         protocol_num = True
     95 
     96         while protocol_num:
     97             if  local_var_select_number  < str(len(local_var_num)):
     98                 print('Your select protocol : < %s > '% local_var_file_name[int(local_var_select_number)])
     99                     # 拼接路径
    100                 temp_var_path_string = local_var_cwd +'\'+ local_var_file_name[int(local_var_select_number)]
    101                 # print('temp_var_path_string:  %s '% temp_var_path_string)
    102                 protocol_num = False
    103                 global_var_file_name_file = temp_var_path_string
    104 
    105             else:
    106                 print('请选择可以执行的协议!')
    107                 protocol_num = True
    108 
    109         return global_var_file_name_file  # 出口
    110 
    111 #
    112 
    113 # ============================================================================
    114 
    115 '''
    116 # ============================================================================
    117 #   测试专用
    118 # ============================================================================
    119 '''
    120 if __name__ == "__main__":
    121     print('测试开始')
    122     '''
    123     # 读取当前文件下,Excel文件
    124     '''
    125     aa = Class_File_Read()
    126     # asd = aa.Methods_File_Operation_Standard()
    127     # aa.Methods_File_Operation_Actual()
    128     asd = aa.Methods_Select_File("1")
    129     print('Path: <%s> '%(asd))
    130     print('测试完成')

     -------

    -----------------------------------------------------------

    API

    -------

    # coding=utf-8
    # ---------------------------------
    '''
    # Author  : chu ge
    # Function:
    #
    '''
    # ---------------------------------
    '''
    # ------------------------------------------
    # 导入模块 
    # 1.系统库
    # 2.第三方库
    # 3.相关定义库
    # ------------------------------------------
    '''
    # 1.系统库
    import sys
    import os
    import re
    
    # 2.第三方库
    # 读取 Excel 模块
    import xlrd
    import xlwt
    import logging
    
    '''
    # ------------------------------------------
    # 导入:同级不同文件夹  
    # 先文件夹__init__注释,其次引用name.py 
    # 最后 使用具体 类class 或者 函数function 名称 
    # ------------------------------------------
    '''
    import Test_Log
    
    '''
    # ------------------------------------------
    # 导入:同级同文件夹  
    # 先引用name.py 
    # 后 使用具体 类class 或者 函数function 名称 
    # ------------------------------------------
    '''
    import Testing_Read_Path
    
    #
    '''
    # ============================================================================
    # Class   :    类
    # Explain :  输入参数  
    #         :  输出参数  
    # ============================================================================
    '''
    class Class_Module_Read(object):
        def __init__(self):
            print()
    
        def Methods_Excel_Data(self, file_path, colnameindex=0, by_name=u'Sheet1'):  # 修改自己路径
            # print('Function_Excel_Table_Byname')
            # ---------------------------------------------------------------------------------------
            self.File = file_path  # 路径名称变换
            # 路径
            # print("路径",self.File)
            # ---------------------------------------------------------------------------------------
            local_list_line = []
            # Methods_Excel_Data
            try:
                # --------------------------------------------------------------------------------------
                local_var_temp_data = xlrd.open_workbook(self.File)  # 打开电子文档  目的:响应删除函数
                # # 这里可以拓展,使用一个Excel 利用不同表格,可以减少外部表格的数量,与上述打开表格方式 是不同的
                local_var_temp_table = local_var_temp_data.sheet_by_name(by_name)  # 获得表格 Excel中不同表格
                # # Contains the data for one worksheet
                local_var_total_rows = local_var_temp_table.nrows  # 属性 拿到总共行数
                # print('total_rows:  < %d >' % local_var_total_rows)               # display
                # # Returns a slice of the values of the cells in the given line
                local_var_column_names = local_var_temp_table.row_values(colnameindex, 0,
                                                                         6)  # 某一列数据 ['', '', '', ''] 默认从0行开始
                # print('line num: < %s >   names:  < % s >'% (len(local_var_column_names),local_var_column_names))
    
                for temp_num in range(1, local_var_total_rows):  # 也就是从Excel第二行开始,第一行表头不算
                    local_var_row = local_var_temp_table.row_values(temp_num)  # 返回单元格中切片
                    # print('rows_num: < %s >  line_num: < %s >  each_element' % (temp_num ,len(local_var_row)),local_var_row )  # 每row 就是列表
    
                    # 每行分片成列表, 列表转变成字典, 字典转变成列表
                    local_dictionary_app = dict(zip(local_var_column_names, local_var_row))  # 列表变字典
                    # print('local_dictionary_app: ',local_dictionary_app)
                    local_list_line.append(local_dictionary_app)  # 字典转变成列表
    
                # # 内部的字典变成了元素
                # print('local_list_line: ',local_list_line)  #打印列表元素
                return local_list_line
            except Exception:
                print("捕获异常:
    位置:<%s>
    目录:<%s>" % ("Methods_Excel_Data", os.getcwd()))
    
        def Methods_Excel_Data_Display(self, file_path):
            local_list_line = self.Methods_Excel_Data(file_path)
            # 遍历列表中的元素  显示成表格模式
            for line in local_list_line:
                print('行号编码:< %s >  %s' % (local_list_line.index(line), line))
                # pprint.pprint(line)  # 规则打印数据
            # 返回列表 并且列表的元素是字典
    
    #
    '''
    # ============================================================================
    # Class   :    类
    # Explain :  输入参数  表格数据
    #         :  输出参数  分表格
    # ============================================================================
    '''
    class Class_Module_Tlabe(object):
        def __init__(self):
            File_Path = Testing_Read_Path.Class_File_Read()  # 路径对象 path
            self.local_var_path_standard = File_Path.Methods_File_Operation_Standard()
            self.local_var_path_actual = File_Path.Methods_File_Operation_Actual()
            self.Log_Display = Test_Log.Test_Save_log.Class_Log_Display()
            self.Log_Display.Methods_BasicConfig()
    
    
        def Methods_Table_Standard(self):
            # Methods_Table_Standard
            try:
                File_Read = Class_Module_Read()  # Excel data 对象
                Table_Standard = File_Read.Methods_Excel_Data(self.local_var_path_standard)
                return Table_Standard
            except Exception:
                print("捕获异常:
    位置:<%s>
    目录:<%s>" % ("Methods_Table_Standard", os.getcwd()))
    
        def Methods_Table_Actual(self):
            # Methods_Table_Actual
            try:
                File_Read = Class_Module_Read()  # Excel data 对象
                Table_Actual = File_Read.Methods_Excel_Data(self.local_var_path_actual)
                return Table_Actual
            except Exception:
                print("捕获异常:
    位置:<%s>
    目录:<%s>" % ("Methods_Table_Actual", os.getcwd()))
        #
        # 搜索actual 中循环搜索的词条,逐个与全部的标准库进行对比
        def Methods_Search_Actual_To_Standard(self):
            Table_Actual = self.Methods_Table_Actual()
            local_error_line_list = []
    
            Feature = self.Methods_Feature_Select()
    
            # Actual_To_Standard
            try:
                local_var_order_count = 0  # 初始化计数
                print("Total Actual Line : < %d >" % len(Table_Actual))
                for Var_A_Element in Table_Actual:
                    local_var_order_count += 1
    
                    # 这里是对比的源头
                    # 添加规则正则表达,首字母
                    try:
                        Is_Capital =self.Methods_Capital_Word(Var_A_Element[1])
                        if Is_Capital == True:
                            A1 = self.Methods_Search_Standard(1, Var_A_Element[1])  # 第1列  备注 第0列开始
                        else:
                            A1 = None
                    except Exception:
                        print("123")
    
                    A2 = self.Methods_Search_Standard(2, Var_A_Element[2])  # 第2列
                    # 功能选择处
                    if Feature == "1":
                        A3 = "1"
                    else:
                        A3 = self.Methods_Search_Standard(3, Var_A_Element[3])  # 第3列
    
                    print('*' * 20)
                    print('line Number : <%d>' % (local_var_order_count + 1))
                    logging.info('
    line Number : [%d]
    %s' % ((local_var_order_count + 1),"one sql end"))
    
                    if ((A1 == "1") and (A2 == "1") and(A3 == "1")) != 0:
                        print('本词条测试结束')
                        print("--" * 20)
                    else:
                        print('词条有错误!!!  请查找原因 !!!')
                        print("--" * 20)
                        local_error_line_list.append(local_var_order_count)
    
                # test message total
                print("Test Message Total")
                for var_line in local_error_line_list:
                    print("Error line: %s" % (var_line + 1))         # 对应Excel
                    logging.info("Error line: %s" % (var_line + 1))
                print("Total Num : <%s>" % len(local_error_line_list))
                logging.info("Total Num : <%s>" % len(local_error_line_list))
    
            except Exception:
                print("捕获异常:
    位置:<%s>
    目录:<%s>" % ("Actual_To_Standard", os.getcwd()))
    
        def Methods_Search_Standard(self, line, entry):
            Table_Standard = self.Methods_Table_Standard()
            self.loacl_var_line = line
            self.local_var_entry = entry
            Local_var_count = 1
            # Search_Actual_To_Standard
            try:
                # 单个思路:获取到对值进行匹配,此值作为对比的标点,标准库作为标靶
                # 搜索匹配功能,遍历每行,对应元素进行匹配,这是关键
                # 最后返回提示量
                for Var_A_Element in Table_Standard:
                    # 有词条且词条不为空
                    if (self.local_var_entry == Var_A_Element[self.loacl_var_line]) != 0:
                        Local_Test_Flag = "1"
                        return Local_Test_Flag
                    else:
                        Local_Test_Flag = "0"
                        Local_var_count += 1
                # 调试时,打开打印
                print("Error name:<%s>" % self.local_var_entry)
                logging.info("
    Error column: <%d>
    词条名称  : <%s>" %(self.loacl_var_line,self.local_var_entry) )
            except Exception:
                print("捕获异常:
    位置:<%s>
    目录:<%s>" % ("Search_Actual_To_Standard", os.getcwd()))
    
        # 功能选择函数
        def Methods_Feature_Select(self):
            # 1.feature 1和2列对比(默认)
            # 2.feature 1、2和3列对比
            print("Feature Select:
    [%s]
    [%s]"%("1.feature 1和2列对比(默认)","2.feature 1、2和3列对比"))
            # Feature_Name = input(">>: ")
            Feature_Name = "1"  #调试固定
            if Feature_Name >"3" :
                Feature_Name = "1"
    
            return Feature_Name
    
        #首字母大写特地检查
        def Methods_Capital_Word(self,column1):
            result_value = re.match(r"[A-Z]",column1)
            if result_value:
                result = True
                # result = result2.istitle()
            else:
                result = False
    
            # print("首字母大写特地检查:",result)
    
            return result
    
    
    #
    '''
    # ============================================================================
    # Function:  Function_Excel_Data  函数
    # Explain :  输入参数   对象 列表的字典
    #         :  输出参数  被调用
    # ============================================================================
    '''
    def Function_Excel_Data():
        # Function_Excel_Data
        try:
            File_Path = Testing_Read_Path.Class_File_Read()  # 路径对象 path
            local_var_path_standard = File_Path.Methods_File_Operation_Standard()
            local_var_path_actual = File_Path.Methods_File_Operation_Actual()
            #
            File_Read = Class_Module_Read()  # Excel data 对象
            # Table_Standard = File_Read.Methods_Excel_Data(local_var_path_standard)
            # Table_Actual   = File_Read.Methods_Excel_Data(local_var_path_actual)
            File_Read.Methods_Excel_Data_Display(local_var_path_standard)
            File_Read.Methods_Excel_Data_Display(local_var_path_actual)
        except Exception:
            print("捕获异常:
    目录:<%s>
    位置:<%s>" % ("Function_Excel_Data", os.getcwd()))
    
    #
    
    # ============================================================================
    
    '''
    # ============================================================================
    #   测试专用
    # ============================================================================
    '''
    if __name__ == "__main__":
        print('测试开始')
        # ============================
        Table_data = Class_Module_Tlabe()
        Table_data.Methods_Search_Actual_To_Standard()
    
        print('测试完成')

     --

    ------------------------------------------------

    结束

  • 相关阅读:
    C#动态显示时间
    死锁问题
    TCP_NODELAY算法使用事项
    二叉搜索树的后序遍历
    从上到下打印二叉树
    栈的压入、弹出序列
    包含min函数的栈
    顺时针打印矩阵
    树的子结构
    合并两个排序链表
  • 原文地址:https://www.cnblogs.com/caochucheng/p/9960412.html
Copyright © 2011-2022 走看看