Python EXCEL 自动化比较文件

Python办公自动化|光速对比并提取两份Word/Excel中的不同元素 如果你经常与Excel或Word打交道,那么从两份表格/文档中找到不一样的元素是一件让人很头疼的工作,当然网上有很多方法、第三方软件教你如何对比两份文件。本文就将以两份真实的Excel/Word文件为例,讲解如何使用Python光速对比并提取文件中的不同之处! 比较Excel 为了方便说明,我创建了一个简单的Excel用于示例 可以看到上方两个Excel表格中共有五处不同,现在我们使用Python来快速定位这五处不同,这次不需要openpyxl,使用Pandas就能轻松搞定,首先导入相关库并读取数据。最后 阅读详情

方法主要函数介绍

openpyxl.load_workbook() 是 Python 中用于处理 Excel 文件的核心函数之一,属于 openpyxl 库(专门用于读写 Excel 2010+ xlsx/xlsm/xltx/xltm 文件的库)。


函数原型

openpyxl.load_workbook(
    filename, 
    read_only=False, 
    keep_vba=False, 
    data_only=False, 
    keep_links=True,
    rich_text=False
)

参数详解

参数类型默认值说明
filenamestr必填Excel 文件路径(支持相对/绝对路径)
read_onlyboolFalse是否以只读模式打开(大文件优化)
✅ 优点:内存占用低
❌ 缺点:不能修改/保存文件
keep_vbaboolFalse是否保留 VBA 宏代码
(保存时需用 .xlsm 扩展名)
data_onlyboolFalse是否读取单元格的计算结果(而非公式)
例:A1=SUM(B1:C1) → 若 data_only=True 则返回计算结果
keep_linksboolTrue是否保留外部链接(如数据库连接)
rich_textboolFalse是否保留富文本格式(如加粗/颜色)

返回值

  • Workbook 对象:代表整个 Excel 工作簿
    • 关键属性:
      wb.sheetnames      # 所有工作表名称列表
      wb.active          # 当前活动工作表
      wb.properties      # 文档元数据(作者/标题等)
      wb.worksheets      # 所有工作表对象的列表
      

使用示例

基础用法
from openpyxl import load_workbook

# 加载工作簿
wb = load_workbook("sales_data.xlsx")

# 获取工作表
ws = wb["Q1_Report"]  # 按名称获取
# 或
ws = wb.active         # 获取活动工作表

# 读取单元格值
cell_value = ws["B2"].value
print(cell_value)  # 输出: 15000

# 遍历行
for row in ws.iter_rows(min_row=2, values_only=True):
    print(row)  # 输出每行数据元组

# 关闭工作簿(释放内存)
wb.close()
高级场景

1. 只读模式处理大文件

wb = load_workbook("big_data.xlsx", read_only=True)
ws = wb.active

# 流式读取(避免内存溢出)
for row in ws.iter_rows(values_only=True):
    process(row)  # 自定义处理函数

wb.close()  # 必须显式关闭!

2. 获取公式计算结果

wb = load_workbook("financial_model.xlsx", data_only=True)
ws = wb["Calculations"]

# 读取 A1 单元格的计算结果(非公式)
result = ws["A1"].value  
print(result)  # 输出: 285000(假设公式已计算)

3. 保留 VBA 宏

wb = load_workbook("macro_enabled.xlsm", keep_vba=True)

# 修改数据(不影响宏)
ws = wb["Dashboard"]
ws["C3"] = "Updated"

# 保存时必须用 .xlsm 扩展名
wb.save("modified_macro.xlsm")  

关键特性

  1. 延迟加载 (Lazy Loading)
    默认只加载工作簿结构,实际数据在访问时按需读取

  2. 内存优化
    只读模式下使用磁盘缓存,适合处理 100MB+ 的大文件

  3. 格式保留
    完整保留单元格样式、数字格式、条件格式等

  4. 公式支持
    可读取公式文本(data_only=False)或计算结果(data_only=True)


注意事项

  1. 文件关闭
    务必在操作完成后调用 wb.close() 释放资源(尤其只读模式)

  2. 公式计算限制
    data_only=True 只能获取 Excel 已计算的结果(若文件未保存过可能返回 None)

  3. 密码保护
    不支持加密文件(需先用其他工具解密)

  4. 性能陷阱
    避免在循环中重复访问同一单元格:

    # 低效写法 ❌
    for i in range(1000):
        val = ws.cell(row=i, column=1).value
    
    # 高效写法 ✅
    data = list(ws.iter_rows(values_only=True))
    

替代方案对比

场景推荐工具原因
简单读写pandas.read_excel()更简洁的 API
超大文件 (>500MB)openpyxl.read_only内存效率最高
旧版 .xls 文件xlrd兼容老格式
高性能需求libreoffice --convert-to命令行批量转换

最佳实践建议

  1. 上下文管理器(自动关闭文件)

    from openpyxl import load_workbook
    
    with load_workbook("data.xlsx") as wb:
        ws = wb.active
        print(ws["A1"].value)
    # 退出 with 块自动关闭
    
  2. 错误重试机制

    from openpyxl.utils.exceptions import InvalidFileException
    
    try:
        wb = load_workbook("corrupted.xlsx")
    except InvalidFileException:
        print("文件损坏或格式不支持")
    
  3. 类型转换辅助

    from openpyxl.cell.cell import TYPE_FORMULA, TYPE_NUMERIC
    
    cell = ws["D5"]
    if cell.data_type == TYPE_FORMULA:
        print("公式:", cell.value)
    elif cell.data_type == TYPE_NUMERIC:
        print("数值:", cell.value)
    

完整案例

第一层:Sheet关系确认

输入:两个Excel文件
输出:DataFrame包含:
- 匹配的sheet对
- 仅存在于文件1的sheet
- 仅存在于文件2的sheet
- 状态标记(一致/不一致)

第二层:内容区域检测

输入:匹配的sheet对
处理:动态检测有效数据区域,查找最早有数据和最晚有数据的单元格
输出:
- 每个sheet的数据边界(起始/结束单元格)
- 边界变化报告
- 共同比较区域

第三层:精细化比对

输入:共同比较区域内的数据
比较方法:所有单元格都字符串处理除前后空格后比较是否一致
输出:
- 差异位置明细(sheet名、行列坐标、原值、新值)
- 差异统计汇总

V 1.0

import pandas as pd
import numpy as np
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
import os

class ExcelComparator:
    def __init__(self, file1_path, file2_path):
        self.file1_path = file1_path
        self.file2_path = file2_path
        self.sheet_comparison_result = None
        self.boundary_comparison_result = None
        self.cell_comparison_result = None
        
    def compare_sheets_info(self):
        """第一层:Sheet关系确认"""
        try:
            # 读取两个Excel文件的所有sheet名称
            wb1 = load_workbook(self.file1_path, read_only=True, data_only=True)
            wb2 = load_workbook(self.file2_path, read_only=True, data_only=True)
            
            sheets1 = set(wb1.sheetnames)
            sheets2 = set(wb2.sheetnames)
            
            # 找出共同的、独有的sheet
            common_sheets = sheets1.intersection(sheets2)
            only_in_file1 = sheets1 - sheets2
            only_in_file2 = sheets2 - sheets1
            
            # 构建结果DataFrame
            results = []
            
            # 共同的sheet
            for sheet in sorted(common_sheets):
                results.append({
                    'file1_sheet': sheet,
                    'file2_sheet': sheet,
                    'status': '匹配',
                    '备注': ''
                })
            
            # 仅在文件1中的sheet
            for sheet in sorted(only_in_file1):
                results.append({
                    'file1_sheet': sheet,
                    'file2_sheet': '',
                    'status': '仅文件1有',
                    '备注': f'文件2中缺少此sheet'
                })
            
            # 仅在文件2中的sheet
            for sheet in sorted(only_in_file2):
                results.append({
                    'file1_sheet': '',
                    'file2_sheet': sheet,
                    'status': '仅文件2有',
                    '备注': f'文件1中缺少此sheet'
                })
            
            self.sheet_comparison_result = pd.DataFrame(results)
            wb1.close()
            wb2.close()
            return self.sheet_comparison_result
            
        except Exception as e:
            print(f"比较sheet信息时出错: {e}")
            return None
    
    def find_data_boundaries(self, worksheet):
        """查找工作表中的数据边界"""
        min_row, max_row, min_col, max_col = None, None, None, None
        
        for row in worksheet.iter_rows():
            for cell in row:
                if cell.value is not None and str(cell.value).strip() != '':
                    if min_row is None or cell.row < min_row:
                        min_row = cell.row
                    if max_row is None or cell.row > max_row:
                        max_row = cell.row
                    if min_col is None or cell.column < min_col:
                        min_col = cell.column
                    if max_col is None or cell.column > max_col:
                        max_col = cell.column
        
        return min_row, max_row, min_col, max_col
    
    def compare_sheet_boundaries(self, sheet_pairs=None):
        """第二层:内容区域检测"""
        try:
            wb1 = load_workbook(self.file1_path, read_only=True, data_only=True)
            wb2 = load_workbook(self.file2_path, read_only=True, data_only=True)
            
            results = []
            
            # 如果没有提供sheet对应关系,使用名称相同的sheet
            if sheet_pairs is None:
                common_sheets = set(wb1.sheetnames).intersection(set(wb2.sheetnames))
                sheet_pairs = [(sheet, sheet) for sheet in common_sheets]
            
            for sheet1_name, sheet2_name in sheet_pairs:
                if sheet1_name not in wb1.sheetnames:
                    results.append({
                        'sheet1_name': sheet1_name,
                        'sheet2_name': sheet2_name,
                        'status': '错误',
                        'sheet1_boundary': 'N/A',
                        'sheet2_boundary': 'N/A',
                        'comparison_area': 'N/A',
                        '备注': f'文件1中找不到sheet: {sheet1_name}'
                    })
                    continue
                    
                if sheet2_name not in wb2.sheetnames:
                    results.append({
                        'sheet1_name': sheet1_name,
                        'sheet2_name': sheet2_name,
                        'status': '错误',
                        'sheet1_boundary': 'N/A',
                        'sheet2_boundary': 'N/A',
                        'comparison_area': 'N/A',
                        '备注': f'文件2中找不到sheet: {sheet2_name}'
                    })
                    continue
                
                ws1 = wb1[sheet1_name]
                ws2 = wb2[sheet2_name]
                
                # 查找数据边界
                min_row1, max_row1, min_col1, max_col1 = self.find_data_boundaries(ws1)
                min_row2, max_row2, min_col2, max_col2 = self.find_data_boundaries(ws2)
                
                # 处理空sheet的情况
                if min_row1 is None:
                    sheet1_boundary = "空sheet"
                else:
                    sheet1_boundary = f"{get_column_letter(min_col1)}{min_row1}:{get_column_letter(max_col1)}{max_row1}"
                
                if min_row2 is None:
                    sheet2_boundary = "空sheet"
                else:
                    sheet2_boundary = f"{get_column_letter(min_col2)}{min_row2}:{get_column_letter(max_col2)}{max_row2}"
                
                # 确定比较区域
                if min_row1 is None and min_row2 is None:
                    status = "一致"
                    comparison_area = "两个sheet都为空"
                    note = ""
                elif min_row1 is None or min_row2 is None:
                    status = "不一致"
                    comparison_area = "N/A"
                    note = "一个sheet有数据,另一个为空"
                else:
                    # 计算共同比较区域
                    comp_min_row = min(min_row1, min_row2)
                    comp_max_row = max(max_row1, max_row2)
                    comp_min_col = min(min_col1, min_col2)
                    comp_max_col = max(max_col1, max_col2)
                    comparison_area = f"{get_column_letter(comp_min_col)}{comp_min_row}:{get_column_letter(comp_max_col)}{comp_max_row}"
                    
                    if min_row1 == min_row2 and max_row1 == max_row2 and min_col1 == min_col2 and max_col1 == max_col2:
                        status = "一致"
                        note = "数据边界完全一致"
                    else:
                        status = "边界不一致"
                        note = "数据边界发生变化"
                
                results.append({
                    'sheet1_name': sheet1_name,
                    'sheet2_name': sheet2_name,
                    'status': status,
                    'sheet1_boundary': sheet1_boundary,
                    'sheet2_boundary': sheet2_boundary,
                    'comparison_area': comparison_area,
                    '备注': note
                })
            
            self.boundary_comparison_result = pd.DataFrame(results)
            wb1.close()
            wb2.close()
            return self.boundary_comparison_result
            
        except Exception as e:
            print(f"比较数据边界时出错: {e}")
            return None
    
    def compare_cells_in_sheets(self, sheet_pairs=None):
        """第三层:精细化单元格比对"""
        try:
            wb1 = load_workbook(self.file1_path, read_only=True, data_only=True)
            wb2 = load_workbook(self.file2_path, read_only=True, data_only=True)
            
            all_differences = []
            summary = []
            
            # 如果没有提供sheet对应关系,使用名称相同的sheet
            if sheet_pairs is None:
                common_sheets = set(wb1.sheetnames).intersection(set(wb2.sheetnames))
                sheet_pairs = [(sheet, sheet) for sheet in common_sheets]
            
            for sheet1_name, sheet2_name in sheet_pairs:
                if sheet1_name not in wb1.sheetnames or sheet2_name not in wb2.sheetnames:
                    continue
                
                ws1 = wb1[sheet1_name]
                ws2 = wb2[sheet2_name]
                
                # 查找数据边界
                min_row1, max_row1, min_col1, max_col1 = self.find_data_boundaries(ws1)
                min_row2, max_row2, min_col2, max_col2 = self.find_data_boundaries(ws2)
                
                # 跳过空sheet
                if min_row1 is None and min_row2 is None:
                    summary.append({
                        'sheet_name': sheet1_name,
                        'total_cells': 0,
                        'differences': 0,
                        'difference_rate': '0%'
                    })
                    continue
                elif min_row1 is None or min_row2 is None:
                    summary.append({
                        'sheet_name': sheet1_name,
                        'total_cells': 'N/A',
                        'differences': 'N/A',
                        'difference_rate': '边界不一致'
                    })
                    continue
                
                # 确定比较区域
                comp_min_row = min(min_row1, min_row2)
                comp_max_row = max(max_row1, max_row2)
                comp_min_col = min(min_col1, min_col2)
                comp_max_col = max(max_col1, max_col2)
                
                differences_count = 0
                total_cells = 0
                
                # 遍历比较区域内的所有单元格
                for row in range(comp_min_row, comp_max_row + 1):
                    for col in range(comp_min_col, comp_max_col + 1):
                        total_cells += 1
                        
                        # 获取单元格值
                        try:
                            val1 = ws1.cell(row=row, column=col).value
                            val2 = ws2.cell(row=row, column=col).value
                        except:
                            val1 = None
                            val2 = None
                        
                        # 转换为字符串并去除前后空格
                        str_val1 = str(val1).strip() if val1 is not None else ""
                        str_val2 = str(val2).strip() if val2 is not None else ""
                        
                        # 比较
                        if str_val1 != str_val2:
                            differences_count += 1
                            all_differences.append({
                                'sheet_name': sheet1_name,
                                'cell_address': f"{get_column_letter(col)}{row}",
                                'file1_value': str_val1 if str_val1 else '(空)',
                                'file2_value': str_val2 if str_val2 else '(空)'
                            })
                
                # 计算差异率
                if total_cells > 0:
                    diff_rate = f"{(differences_count / total_cells * 100):.2f}%"
                else:
                    diff_rate = "0%"
                
                summary.append({
                    'sheet_name': sheet1_name,
                    'total_cells': total_cells,
                    'differences': differences_count,
                    'difference_rate': diff_rate
                })
            
            self.cell_comparison_details = pd.DataFrame(all_differences)
            self.cell_comparison_summary = pd.DataFrame(summary)
            
            wb1.close()
            wb2.close()
            return self.cell_comparison_details, self.cell_comparison_summary
            
        except Exception as e:
            print(f"比较单元格时出错: {e}")
            return None, None
    
    def run_complete_comparison(self, custom_sheet_pairs=None):
        """执行完整的三层比较"""
        print("=== Excel文件比较报告 ===")
        print(f"文件1: {os.path.basename(self.file1_path)}")
        print(f"文件2: {os.path.basename(self.file2_path)}")
        print()
        
        # 第一层:Sheet关系确认
        print("第一层:Sheet关系确认")
        sheet_info = self.compare_sheets_info()
        if sheet_info is not None:
            print(sheet_info)
            print()
        
        # 第二层:内容区域检测
        print("第二层:内容区域检测")
        boundary_info = self.compare_sheet_boundaries(custom_sheet_pairs)
        if boundary_info is not None:
            print(boundary_info)
            print()
        
        # 第三层:精细化比对
        print("第三层:精细化单元格比对")
        details, summary = self.compare_cells_in_sheets(custom_sheet_pairs)
        if summary is not None:
            print("差异统计汇总:")
            print(summary)
            print()
        
        if details is not None and not details.empty:
            print("差异详情 (前20条):")
            print(details.head(20))
            if len(details) > 20:
                print(f"... 还有 {len(details) - 20} 条差异未显示")
        else:
            print("未发现单元格级别差异")
        
        return sheet_info, boundary_info, details, summary

# 使用示例
if __name__ == "__main__":
    # 初始化比较器
    comparator = ExcelComparator("file1.xlsx", "file2.xlsx")
    
    # 执行完整比较
    sheet_info, boundary_info, cell_details, cell_summary = comparator.run_complete_comparison()
    
    # 如果需要自定义sheet对应关系
    # custom_pairs = [("Sheet1", "Data"), ("Summary", "Report")]
    # sheet_info, boundary_info, cell_details, cell_summary = comparator.run_complete_comparison(custom_pairs)
    
    # 保存结果到Excel(可选)
    # with pd.ExcelWriter('comparison_result.xlsx') as writer:
    #     sheet_info.to_excel(writer, sheet_name='Sheet关系', index=False)
    #     boundary_info.to_excel(writer, sheet_name='数据边界', index=False)
    #     cell_summary.to_excel(writer, sheet_name='差异统计', index=False)
    #     cell_details.to_excel(writer, sheet_name='差异详情', index=False)

使用方法:

# 基本用法
comparator = ExcelComparator("file1.xlsx", "file2.xlsx")
results = comparator.run_complete_comparison()

# 自定义sheet对应关系
custom_pairs = [("Sheet1", "Data"), ("Summary", "Report")]
results = comparator.run_complete_comparison(custom_pairs)
Python办公自动化案例:对比两个Excel数据内容并标出不同 在数据处理和分析的日常工作中,我们经常需要比较两个Excel文件的差异。这可能是为了验证数据的一致性、检查数据的准确性,或者在版本控制中追踪更改。手动比较这些文件不仅耗时,而且容易出错。幸运的是,Python的openpyxl库提供了一种自动化这一过程的方法。 阅读详情

相关推荐

【Python办公】快速比较Excel文件中任意两列数据的一致性

Python Excel数据比较工具开发 本文介绍了一个基于Python的Excel数据比较工具的开发过程,主要功能包括: 核心功能:支持.xlsx和.xls格式文件导入,动态选择任意两列进行比较,自动处理空值和数据类型差异 技术架构:采用tkinter构建GUI界面,pandas处理数据,openpyxl/xlrd读写Excel文件 设计特点: 实时状态反馈和错误提示 结果统计和差异数据展示 一键导出完整比较报告 应用场景:适用于数据迁移验证、系统间数据核对、更新前后数据对比等办公自动化需求

weixin_42636075的博客 618

python:openpyxl 读取 Excel文件,显示在 wx.grid 表格中

python:openpyxl 读取 .xlsx 文件,显示在 wx.grid 表格中。参考了百度:文心一言:openpyxl 示例

belldeep的专栏 972

U盘重装Win10系统

准备工作 准备一个8G或8G以上U盘(32G以内) 请备份好u盘里的资料,在制作过程中会格式化硬盘 请备份好要安装系统的盘的资料,安装时也会对该盘内容进行格式化。 将u盘插入电脑usb接口中,尽可能的插入usb3.0的接口,这样下载和安装速度会更快。 1.到微软官网下载安装包 浏览器输入:微软官网下载win10 懒人请复制粘贴:https://www.microsoft.com/zh-cn/software-download/windows10 ​ 打开之后的界面: 2.下载Media Creat.

Cici$的博客 2116

python openpyxl模块load_workbook()data_only参数

Name: openpyxlVersion: 2.4.8参照官方文档wb = openpyxl.load_workbook(‘abc.xlsx’, data_only=True)当’abc.xlsx’被生成并在Excel程序中打开并保存之后(这个过程Excel会把公式结果计算出来),该文件附带有两套值,一套是公式全都没有计算的(data_only=False(默认)),一套是...

weixin_34101229的博客 1万+

CCS配置MSPM0G3507(七) 编码器(TIMER-QEI)

1.选择时钟源 BUSCLK2.时钟分频配置为1分频3.分频系数配置为14.若勾选 Start ,则生成程序后会自动开启定时器的计数,否则需手动在程序中开启5.Load Value 设置为65535。

kaneki_lh的博客 1万+

永磁同步电机定子槽型设计实战:从梨形槽到矩形槽的NVH优化之路

本文深入探讨了永磁同步电机定子槽型设计在NVH优化中的关键作用,对比了梨形槽与矩形槽的性能差异。通过Ansys Maxwell仿真和实际案例,揭示了矩形槽在提升槽满率、降低电磁噪声方面的优势,并总结了五大设计黄金法则,为电机设计工程师提供了实用指导。

weixin_28740299的博客 494

openpyxl详解

1.创建/读取excel文件 创建excel from openpyxl import Workbook wb = Workbook() 读取excel from openpyxl import load_workbook wb = load_workbook('1.xlsx') 保存excel wb.save('filename.xlsx') 2.sheet表单操作 获取s...

weixin_45198279的博客 3万+

【网络协议】TCP的拥塞控制机制

前言 计算机网络中的带宽、交换节点中的缓存和处理机等,都是网络的资源,在某段时间内,若对网络中某一资源的需求超过了该资源所能提供的可用部分,网络的性能就要变坏,这种情况就叫做拥塞。 所谓拥塞控制,就是防止过多的数据注入到网络中,从而使网络中的路由器或链路不致过载。要注意用拥塞控制与流量控制的区别,拥塞控制是一个全局性的过程,涉及到所有的额主机、路由器,以及与降低网 拥塞控制的算法有:慢开始、拥塞避免、快重传、快恢复四种。 慢开始和拥塞避免 发送方维持一个拥塞窗口的状态变量,其大小取决于网络的拥塞程度

兰亭风雨的专栏 1万+

Python 计算两个 Excel 文件的差异

读取两个 Excel 文件的内容。比较两者的结构(如表头、列名等)。逐行逐列比较数据。输出差异结果。通过 Python 和 Pandas 库,我们可以轻松实现 Excel 文件的差异比较。这种方法不仅提高了效率,还减少了人为错误的可能性。希望本文能帮助您快速上手这一实用技能!如果您有任何疑问或建议,欢迎在评论区留言交流。```

2501_91227282的博客 393

Lenovo 拯救者15ISK硬件升级实战:从内存到固态硬盘的全面优化

本文详细介绍了为联想拯救者15ISK笔记本电脑进行硬件升级的完整实战指南。通过评估升级可行性,指导如何挑选兼容的内存条与NVMe固态硬盘,并提供详细的拆机安装步骤与系统安装避坑技巧。升级后,笔记本的开机速度、软件加载及多任务处理能力获得飞跃式提升,让老旧设备重获新生。

weixin_29310631的博客 558

Allegro如何把分离的线段变成封闭连续的图形

Allegeo支持把分离的线段变成封闭连续的图形,以下图为例,线段是分离的。Allegro如何把分离的线段变成封闭连续的图形。Find选择other segs 和Lines。Find选择other segs 和Lines。选择shape-compose shape。分离线段已经是连续封闭的shape形式了。框选图形,删除剩下的无用的分离线段。Find选择shapes。鼠标右击选择done。选择delete命令。鼠标右击选择done。

weixin_54787054的博客 6244

Python +excel+pandas +openpyxl自动化处理excel表格,自动化办公

最近老是被抓着填一些反反复复的表格,无非就是身份证号啊、电话号码啥的,有没有同感的小伙伴觉得这样很烦人,所以重复的工作能不能交给机器去做~我相信一句至理名言,“未知领域人比机器可靠,重复的工作机器比人可靠。

qq_62618133的博客 1465

传统(经典)粒子群算法(PSO)解决单目标优化问题

智能算法:粒子群算法(particle swarm optimizer)—PSO %原理:(1)种群初始化–N(种群数)–D(个体数)–x(i)(粒子位置)–v(i)(粒子速度) % (2)计算每个粒子的适应度值–而适应度值需要选择适应度函数 % (3)对于每个粒子,使用它的适应度值fit[i]和个体的极值pbest(i)进行比较,如果fit[i]>pbest(i),则pbest(i)=fit[i] % (4)同理,对每个粒子用它的适应值与全局极值进行比较,如果比它大,则

weixin_51631044的博客 1295

python文件查重并合并_用python对excel查重

最近媳妇工作上遇到一个重复性劳动,excel表格查重,重复的标记起来,问我能不能写个程序让它自动查重标记必须安排第一次正儿八经写python,边上网查资料,边写终于成功了在此记录一下首先安装xlwings库pip install xlwings写代码import xlwings as xw# 输入表名title = input()# 指定不显示地打开Excel,读取Excel文件app = xw....

weixin_39550172的博客 294

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

【作者: 艾里艾兰 】Python+requests+unittest+excel实现接口自动化测试框架

原文地址 作者: 艾里艾兰 ailiailan python自动化语言基础 Python自动化--语言基础8--接口请求及封装 Python自动化--语言基础7--操作日志、加密、发送邮件、线程、生产者消费者 Python自动化--语言基础6--模块操作之re、MySQL、Excel Python自动化--语言基础5--面向对象、迭代器、range和切片的区分 Python自动化--语...

lelemom的博客 2624

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

python 读取excel数据并将测试结果填入Excel

python 读取excel数据并将测试结果填入Excel 读取一个Excel中的一条数据用例,请求接口,然后返回结果并反填到excel中。过程中会生成请求回来的文本,当然还会生成一个xml文件。具体的excel文件如下: 代码如下: # -*- coding: UTF-8 -*- from xml.dom import minidom import xlrd import ...

weixin_30802171的博客 693

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

Python利用Excel读取和存储测试数据完成接口自动化教程

作为一位过来人也是希望大家少走一些弯路,如果你不想再体验一次学习时找不到资料,没人解答问题,坚持几天便放弃的感受的话,在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。

2301_77645834的博客 574

python excel案例导入jira_python实战一:将excel数据导入到jira

excel&jira同步背景:第三方测试会以excel形式提交buglist,这个buglist需要同步到jira中,在jira进行跟踪,并将处理结果反馈给第三方;以往都是复制粘贴,为了减轻繁琐的操作,提高工作效率,这次要使用脚本通过jira的接口进行同步因开发时间有限,不能完全实现自动化,本文仅解决将指定excel中的数据导入jira,后续有时间再做优化:1.将jira.bug的解决状态...

weixin_39522170的博客 644

python 自动填excel_Python读写Excel自动填表

前面一篇文章提到:Excel复杂排序业务实战对于非程序员来说,基本也只能这样操作了,对于程序员,写个小工具不成问题,这里用Python写个Excel账单自动填表,可以省掉很多事需要准备的Python库xlrd读Excelxlwt写Excelxlutils是Excel工具库,安装这个库的前提是安装了xlrd和xlwt,安装很简单Python2.7下三个pip命令搞定pip install xlrdp...

weixin_39904809的博客 327

Python Excel 比较 sheet 之间的差异

实现快速输出比较两个excel(可能是xlsx、xls、xlsb、xlsm或者csv)中指定的sheet中列内容是否一致。假定每个sheet的第一行是标题行,如果一致则输出相同的信息,如果有不一致则输出一个结果分析的xlsx文件。

RandPython的博客 623

python比较两个excel表格的差异

一个同事有两个excel表格要比较差异, 找了一下有相关软件,如: beyond compare, excel compare 但这两个似乎都是直接排序再比较的. 然后没办法,就用python折腾了一个脚本. 这个脚本先读入要比较的文件中的表. 读的时候 ,如果没有空行就把它和它前面的加一起,直到有空行. 这样比较的话, 不能得到具体那一行有差异, 只...

weixin_34004576的博客 4612
上一篇: Python运行日记汇总小技巧
下一篇: Python EXCEL 半自动化切分数据集
偷心伊普西隆
博客等级 码龄7年 511粉丝 65原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值