一鍵凈化Excel數據:高性能Python腳本實現多核并行清理

摘要

本文分享兩個基于Python的Excel數據凈化腳本,通過多進程并行技術清除工作表內不可見字符、批注、單元格樣式等冗余內容,利用OpenPyXL實現底層操作,結合tqdm進度條和進程級任務分配,可快速處理百萬級單元格數據。適用于數據分析預處理、跨系統數據遷移等場景。

腳本一:并行處理統一(單)進度條版本

架構設計:

主進程
初始化進程池
分配工作表任務
進程1處理整表
進程2處理整表
單元格清洗流水線
清除不可見字符
移除批注
重置樣式
保存臨時文件
合并處理結果

源碼:

import openpyxl
from openpyxl.styles import NamedStyle, Font, Border, PatternFill
from openpyxl.formatting import Rule
import re
from tqdm import tqdm
import multiprocessing
from functools import partialdef clean_invisible_chars(text):"""清除字符串中的不可見字符"""if not isinstance(text, str):return textreturn re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)def process_cell(cell, no_style, no_fill, cleared_list):"""處理單個單元格的并行化函數"""# 清除單元格所有樣式cell.fill = no_fillcell.font = Font(name='Calibri', size=11, bold=False, italic=False)cell.border = Border()cell.number_format = 'General'# 清除不可見字符if cell.value and isinstance(cell.value, str):cell.value = clean_invisible_chars(cell.value)cleared_list.append('不可見字符')# 清除批注if cell.comment:cell.comment = Nonecleared_list.append('批注')# 清除樣式cell.style = no_stylecleared_list.append('單元格樣式')def process_sheet(args):"""處理整個工作表的并行化函數"""input_file, output_file, sheet_name = argscleared_items = set()# 每個進程獨立處理一個完整的工作表wb = openpyxl.load_workbook(input_file)ws = wb[sheet_name]no_style = NamedStyle(name="Normal")no_fill = PatternFill(fill_type=None)# 清除所有條件格式ws.conditional_formatting = []cleared_items.add('條件格式填充色')total_rows = ws.max_rowtotal_cols = ws.max_column# 使用tqdm顯示進度for row in tqdm(ws.iter_rows(), total=total_rows, desc=f"處理 {sheet_name}"):for cell in row:# 清除單元格所有樣式cell.fill = no_fillcleared_items.add('背景填充色')cell.font = Font(name='Calibri', size=11, bold=False, italic=False)cell.border = Border()cell.number_format = 'General'cell.style = no_stylecleared_items.add('單元格樣式')# 清除不可見字符if cell.value and isinstance(cell.value, str):cell.value = clean_invisible_chars(cell.value)cleared_items.add('不可見字符')# 清除批注if cell.comment:cell.comment = Nonecleared_items.add('批注')# 保存臨時文件temp_file = f"temp_{sheet_name}.xlsx"wb.save(temp_file)return (temp_file, sheet_name, list(cleared_items))def clear_all_and_save(input_file, output_file, sheet_name, num_processes=None):"""多進程并行清除工作表中的:1. 不可見字符2. 批注3. 單元格樣式"""if num_processes is None:num_processes = multiprocessing.cpu_count()print(f"使用 {num_processes} 個進程并行處理...")# 準備參數 (這里可以擴展為處理多個sheet)args = [(input_file, output_file, sheet_name)]# 創建進程池with multiprocessing.Pool(processes=num_processes) as pool:results = list(tqdm(pool.imap(process_sheet, args), total=len(args), desc="總進度"))# 合并處理結果cleared_items = set()for temp_file, sheet_name, items in results:cleared_items.update(items)# 這里可以添加合并多個臨時文件的邏輯# 保存最終工作簿 (簡化處理,直接使用第一個結果)import shutilshutil.move(results[0][0], output_file)cleared_text = "\n".join(f"  ? 清除-{item}" for item in cleared_items)print("已完成:\n"+cleared_text+f"\n并保存到 {output_file}")if __name__ == '__main__':input_excel_file = '測試文件.xlsx' # 原始文件output_excel_file = '清除樣式_測試文件_并行版.xlsx' # 生成文件sheet_to_clean = 'sheet1' # sheet nameprint(f"輸入文件: {input_excel_file}")print(f"輸出文件: {output_excel_file}")print(f"目標工作表: {sheet_to_clean}")try:clear_all_and_save(input_excel_file, output_excel_file, sheet_to_clean)except Exception as e:print(f"處理過程中發生錯誤: {str(e)}")

腳本二:多核獨立進度條版本

架構設計:

主進度條
啟動N個Worker進程
進程0進度條
進程1進度條
單元格樣式處理器
字符過濾器
批注清除器
生成校驗日志
多文件聚合器
最終輸出文件

源碼:

import openpyxl
from openpyxl.styles import NamedStyle, Font, Border, PatternFill
from openpyxl.formatting import Rule
import re
from tqdm import tqdm
import multiprocessing
from functools import partialdef clean_invisible_chars(text):"""清除字符串中的不可見字符"""if not isinstance(text, str):return textreturn re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)def process_sheet(args):"""處理整個工作表的并行化函數"""input_file, output_file, sheet_name, process_idx = argscleared_items = set()# 每個進程獨立處理一個完整的工作表wb = openpyxl.load_workbook(input_file)ws = wb[sheet_name]no_style = NamedStyle(name="Normal")no_fill = PatternFill(fill_type=None)# 清除所有條件格式ws.conditional_formatting = []cleared_items.add('條件格式填充色')total_rows = ws.max_rowtotal_cols = ws.max_column# 使用多行進度條(position參數控制行位置)process_idx = args[3]  # 獲取進程索引for row in tqdm(ws.iter_rows(), total=total_rows, desc=f"進程{process_idx}", position=process_idx+1):for cell in row:# 清除單元格所有樣式cell.fill = no_fillcell.font = Font(name='Calibri', size=11, bold=False, italic=False)cell.border = Border()cell.number_format = 'General'cell.style = no_stylecleared_items.update(['背景填充色', '單元格樣式'])# 清除不可見字符if cell.value and isinstance(cell.value, str):cell.value = clean_invisible_chars(cell.value)cleared_items.add('不可見字符')# 清除批注if cell.comment:cell.comment = Nonecleared_items.add('批注')# 保存臨時文件temp_file = f"temp_{sheet_name}.xlsx"wb.save(temp_file)return (temp_file, sheet_name, list(cleared_items))def clear_all_and_save(input_file, output_file, sheet_name, num_processes=None):"""多進程并行清除工作表中的:1. 不可見字符2. 批注3. 單元格樣式"""if num_processes is None:num_processes = multiprocessing.cpu_count()print(f"使用 {num_processes} 個進程并行處理...")# 準備參數并添加進程索引args = [(input_file, output_file, sheet_name, i) for i in range(num_processes)]# 確保至少有一個參數組if not args:args = [(input_file, output_file, sheet_name, 0)]# 創建進程池并顯示總進度with multiprocessing.Pool(processes=num_processes) as pool:# 在主進度條下方顯示各進程進度with tqdm(total=len(args), desc="總進度", position=0) as pbar:results = []for result in pool.imap(process_sheet, args):results.append(result)pbar.update()# 合并處理結果cleared_items = set()for temp_file, sheet_name, items in results:cleared_items.update(items)# 這里可以添加合并多個臨時文件的邏輯# 保存最終工作簿 (簡化處理,直接使用第一個結果)import shutilshutil.move(results[0][0], output_file)cleared_text = "\n".join(f"  ? 清除-{item}" for item in cleared_items)print("已完成:\n"+cleared_text+f"\n并保存到 {output_file}")if __name__ == '__main__':input_excel_file = '測試文件.xlsx' # 原始文件output_excel_file = '清除樣式_測試文件_并行版.xlsx' # 生成文件sheet_to_clean = 'sheet1' # sheet nameprint(f"輸入文件: {input_excel_file}")print(f"輸出文件: {output_excel_file}")print(f"目標工作表: {sheet_to_clean}")try:clear_all_and_save(input_excel_file, output_excel_file, sheet_to_clean)except Exception as e:print(f"處理過程中發生錯誤: {str(e)}")

核心清除能力

  • 數據凈化:過濾ASCII 0-31不可見控制字符
  • 元數據清理:徹底清除單元格批注內容
  • 樣式重置
    • 移除條件格式規則
    • 重置字體為Calibri 11pt
    • 清除所有填充顏色
    • 移除單元格邊框樣式
  • 性能優化
    • 多進程負載均衡
    • 基于CPU核心數自動擴展
    • 無鎖內存獨立操作

適用場景

  1. 第三方系統導出的臟數據清洗
  2. 金融數據脫敏后標準化處理
  3. 跨平臺遷移Excel文件前的格式轉換
  4. 機器學習數據預處理階段
  5. 定期自動化報表生成前的重置

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/83278.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/83278.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/83278.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Netty】EventLoopGroup

在Netty的ServerBootstrap中設置兩個EventLoopGroup的作用是將網絡操作的兩個關鍵階段分離到不同的線程組中處理,從而優化性能并簡化并發控制。具體來說: 1. 兩個EventLoopGroup的角色 第一個EventLoopGroup(通常稱為bossGroup)&…

【前端】Vue中使用CKeditor作為富文本編輯器

官網https://ckeditor.com/ 此處記錄一下我在使用的時候具體初始化的代碼。 <template><div><textarea :id"id"></textarea></div> </template><script> export default {name: CkEditor,data: function () {return {id:…

前端面經 websocket

應用層協議&#xff0c;實現一個TCP連接上的全雙工通信&#xff0c;實時通訊 之前的實時WEB 實現輪詢 增加輪詢頻率 ws wss 明文版本 和 密文版本 特點 # 1 頭部小 2 更注重實時性

【筆記】suna部署之獲取 Supabase API key 和 project URL

#工作記錄 Supabase | The Open Source Firebase Alternative 一、注冊與登錄 方式一&#xff1a;GitHub 授權登錄 在登錄頁面選擇 “繼續使用 GitHub” &#xff0c;跳轉到 GitHub 授權頁面&#xff08;如圖 5 所示&#xff09;。確認 “Supabase 的想要訪問您的 [賬戶名] 帳…

爬蟲工具鏈的詳細分類解析

以下是針對爬蟲工具鏈的詳細分類解析&#xff0c;涵蓋靜態頁面、動態渲染和框架開發三大場景的技術選型與核心特性&#xff1a; &#x1f9e9; 一、靜態頁面抓取&#xff08;HTML結構固定&#xff09; 工具組合&#xff1a;Requests BeautifulSoup 適用場景&#xff1a;目標數…

STM32F407寄存器操作(ADC非連續掃描模式)

1.前言 書接上回&#xff0c;在看手冊的時候我突然發現手冊上還描述了另一種ADC掃描模式&#xff0c;即非連續掃描模式&#xff0c;想著連續掃描模式都已經探索過了&#xff0c;那就順手把非非連續模式研究一下吧。 2.理論 我們先看看手冊&#xff0c;這里我就以規則通道舉例…

spring切面

概念 兩個特點&#xff1a; IOC控制反轉AOP主要用來處理公共的代碼 例如一個案例就是添加用戶&#xff0c;重復的代碼包含了記錄日志、事務提交和事務回滾等&#xff0c;都是重復的&#xff0c;為了簡單&#xff0c;交給AOP來做。 即將復雜的需求分解出不同方面&#xff0c…

[Python] Python中的多重繼承

文章目錄 Lora中的例子 Lora中的例子 https://github.com/michaelnny/QLoRA-LLM/blob/main/qlora_llm/models/lora.py#L211C1-L243C10如果繼承兩個父類&#xff0c;并且父類的__init__參數不一樣&#xff0c;則可以顯式的調用父類init&#xff1b;如果用super().__init__()則需…

rsync服務的搭建

目錄 一、rsync介紹 rsync的安裝 二、rsync的語法 三、rsync命令使用 1. 本機同步 2. 遠程同步 四、rsync作為服務使用 1、嘗試啟動rsync程序 2、rsync的配置文件介紹 注意事項&#xff1a; 3. rsyncinotify實時同步 3.依賴服務托管xinetd&#xff08;CentOS 6中rs…

【C/C++】面試基礎題目收集

C 軟件開發面試中常見的刷題題目通常可分為以下幾大類&#xff1a;數據結構與算法、系統編程、面向對象設計、C 語言特性、并發編程等。 &#x1f9e0; 一、數據結構與算法&#xff08;力扣/牛客經典題&#xff09; 掌握 STL 和底層結構實現能力&#xff1a; &#x1f4cc; 數…

將手機網絡經USB數據線和本地局域網共享給華為AP6050DN無線接入點

引言 由于最近裝畢的新家所在的小區未能及時通寬帶,于是家中各類無線設備如何上網就成了首要要解決的問題。 鑒于家中要聯網的設備多、類型雜、支持頻段也不一,總是開手機熱點不是回事兒,于是就想著把手機網絡引至華為AP6050DN無線接入點中,讓家中所有的無線設備都能快速高…

【數據結構】圖論核心算法解析:深度優先搜索(DFS)的縱深遍歷與生成樹實戰指南?

深度優先搜索 導讀&#xff1a;從廣度到深度&#xff0c;探索圖的遍歷奧秘一、深度優先搜索二、算法思路三、算法邏輯四、算法評價五、深度優先生成樹六、有向圖與無向圖結語&#xff1a;深潛與回溯&#xff0c;揭開圖論世界的另一面 導讀&#xff1a;從廣度到深度&#xff0c;…

Flink CEP實踐總結:使用方法、常見報錯、優化與難點應對

Flink CEP實踐總結&#xff1a;使用方法、常見報錯、優化與難點應對 隨著實時數據分析需求的提升&#xff0c;Flink CEP&#xff08;Complex Event Processing&#xff0c;復雜事件處理&#xff09;成為事件流檢測中的利器。本文結合實際項目經驗&#xff0c;總結Flink CEP的基…

Python數據類型詳解:從字符串到布爾值,一網打盡

Python是現代編程語言中非常流行的一種&#xff0c;它的語法簡潔、易懂&#xff0c;非常適合初學者。而在Python編程中&#xff0c;“數據類型”是最基礎也是最重要的概念。理解這個概念&#xff0c;將為你之后的編程打下堅實的基礎。 1. 什么是數據類型&#xff1f; 在Pytho…

python打卡day42

Grad-CAM與Hook函數 知識點回顧 回調函數lambda函數hook函數的模塊鉤子和張量鉤子Grad-CAM的示例 在深度學習中&#xff0c;我們經常需要查看或修改模型中間層的輸出或梯度&#xff0c;但標準的前向傳播和反向傳播過程通常是一個黑盒&#xff0c;很難直接訪問中間層的信息。PyT…

中國風展示工作總結商務通用PPT模版

中國風展示工作總結商務通用PPT模版&#xff1a;中國風商務通用PPT 模版https://pan.quark.cn/s/42ad18c010d4

TeleAI發布TeleChat2.5及T1正式版,雙雙開源上線魔樂社區!

5月12日&#xff0c;中國電信開源TeleChat系列四個模型&#xff0c;涵蓋復雜推理和通用問答的多個尺寸模型&#xff0c;包括TeleChat-T1-35B、TeleChat-T1-115B、TeleChat2.5-35B和TeleChat2.5-115B&#xff0c;實測模型性能均有顯著的性能效果。TeleChat系列模型基于昇思MindS…

機器視覺2D定位引導一般步驟

機器視覺的2D定位引導是工業自動化中的核心應用,主要用于精確確定目標物體的位置(X, Y坐標)和角度(旋轉角度θ),并引導機器人或運動機構進行抓取、裝配、對位、檢測等操作。其一般步驟可概括如下: 一、系統規劃與硬件選型 明確需求: 定位精度要求(多少毫米/像素,多少…

兒童節快樂,聊聊數字的規律和同余原理

某年的6月1日是星期日。那么&#xff0c;同一年的6月30日是星期幾&#xff1f; 星期是7天一個循環。所以說&#xff0c;這一天是星期幾&#xff0c;7天之后同樣也是星期幾。而6月30日是在6月1日的29天之后&#xff1a;29 7 4 ... 1用29除以7&#xff0c;可以得出余數為1。而…

最佳實踐|互聯網行業軟件供應鏈安全建設的SCA縱深實踐方案

在數字化轉型的浪潮中&#xff0c;開源組件已成為企業構建云服務與應用的基石&#xff0c;但其引入的安全風險也日益凸顯。某互聯網大廠的核心安全研究團隊&#xff0c;通過深度應用軟件成分分析&#xff08;SCA&#xff09;技術&#xff0c;構建了一套覆蓋開源組件全生命周期管…