在本文中,我们将分析一个使用 wxpython 和 pandas 库编写的 python 应用程序,名为 “xlsx analyzer and web opener”。该应用程序的核心功能是:从 excel 文件中读取数据并显示在网格中,此外,还允许用户使用 google chrome 批量打开 excel 文件中的 url 列表。
c:\pythoncode\new\analysisxlsx.py
全部代码
import wx import wx.grid import pandas as pd import subprocess import os chrome_path = r"c:\program files\google\chrome\application\chrome.exe" class xlsxanalyzerframe(wx.frame): def __init__(self): super().__init__(parent=none, title='xlsx analyzer and web opener', size=(1200, 800)) panel = wx.panel(self) main_sizer = wx.boxsizer(wx.vertical) self.file_picker = wx.filepickerctrl(panel, wildcard="excel files (*.xlsx)|*.xlsx") self.file_picker.bind(wx.evt_filepicker_changed, self.on_file_selected) main_sizer.add(self.file_picker, 0, wx.all | wx.expand, 10) self.grid = wx.grid.grid(panel) main_sizer.add(self.grid, 1, wx.all | wx.expand, 10) open_button = wx.button(panel, label='open urls in chrome') open_button.bind(wx.evt_button, self.on_open_urls) main_sizer.add(open_button, 0, wx.all | wx.center, 10) panel.setsizer(main_sizer) self.layout() self.show() self.grid_created = false def on_file_selected(self, event): file_path = self.file_picker.getpath() if file_path: try: df = pd.read_excel(file_path, sheet_name='sheet1') expected_columns = [ "blog-list-box href", "course-img src", "blog-list-box-top", "blog-list-content", "article-type", "view-time-box", "view-num", "give-like-num", "comment-num", "comment-num 2", "btn-edit-article href" ] if not all(col in df.columns for col in expected_columns): raise valueerror("excel file does not contain all expected columns") self.update_grid(df) except exception as e: wx.messagebox(f'error reading file: {str(e)}', 'error', wx.ok | wx.icon_error) def update_grid(self, df): if not self.grid_created: self.grid.creategrid(df.shape[0], df.shape[1]) self.grid_created = true else: current_rows = self.grid.getnumberrows() current_cols = self.grid.getnumbercols() if current_rows < df.shape[0]: self.grid.appendrows(df.shape[0] - current_rows) elif current_rows > df.shape[0]: self.grid.deleterows(0, current_rows - df.shape[0]) if current_cols < df.shape[1]: self.grid.appendcols(df.shape[1] - current_cols) elif current_cols > df.shape[1]: self.grid.deletecols(0, current_cols - df.shape[1]) for i, col in enumerate(df.columns): self.grid.setcollabelvalue(i, str(col)) for j, val in enumerate(df[col]): self.grid.setcellvalue(j, i, str(val)) self.grid.autosizecolumns() self.grid.forcerefresh() self.layout() def get_urls(self): if self.grid.getnumberrows() == 0: wx.messagebox('no data loaded', 'error', wx.ok | wx.icon_error) return [] try: url_col_index = next(i for i in range(self.grid.getnumbercols()) if "blog-list-box href" in self.grid.getcollabelvalue(i)) return [self.grid.getcellvalue(row, url_col_index) for row in range(self.grid.getnumberrows()) if self.grid.getcellvalue(row, url_col_index).strip()] except stopiteration: wx.messagebox('could not find "blog-list-box href" column', 'error', wx.ok | wx.icon_error) return [] def on_open_urls(self, event): if not os.path.exists(chrome_path): wx.messagebox(f'chrome executable not found at {chrome_path}', 'error', wx.ok | wx.icon_error) return urls = self.get_urls() if not urls: return for i in range(0, len(urls), 10): batch = urls[i:i+10] for url in batch: try: subprocess.popen([chrome_path, url]) except exception as e: wx.messagebox(f'error opening url {url}: {str(e)}', 'error', wx.ok | wx.icon_error) if i + 10 < len(urls): should_continue = wx.messagebox('open next 10 urls?', 'continue', wx.yes_no | wx.icon_question) if should_continue == wx.no: break if __name__ == '__main__': app = wx.app() frame = xlsxanalyzerframe() app.mainloop()
核心功能概述
1.选择并解析 xlsx 文件:用户通过文件选择器选择一个 excel 文件,程序读取其中的数据,并在网格中显示。
2.批量打开 url:如果 excel 文件包含一个 url 列,用户可以点击按钮,程序会批量使用 chrome 打开这些 url。
3.错误处理:当文件不符合预期格式,chrome 浏览器不可用或打开 url 失败时,程序会显示相应的错误消息。
导入的库
import wx import wx.grid import pandas as pd import subprocess import os
wx 和 wx.grid:用于创建图形用户界面(gui),包括窗口、文件选择器、按钮和数据网格。
pandas (pd):用于从 excel 文件中读取数据,并处理这些数据以显示在 gui 网格中。
subprocess:用于通过系统命令启动 chrome 浏览器。
os:用于检查 chrome 浏览器的路径是否存在。
google chrome 路径
chrome_path = r"c:\program files\google\chrome\application\chrome.exe"
该常量存储了 chrome 浏览器的路径,程序将使用这个路径来启动 chrome。如果用户的系统上 chrome 位于不同的路径,需要修改该值。
类 xlsxanalyzerframe
主框架类 xlsxanalyzerframe 继承自 wx.frame,实现了应用的 gui 和逻辑。下面是它的初始化部分:
class xlsxanalyzerframe(wx.frame): def __init__(self): super().__init__(parent=none, title='xlsx analyzer and web opener', size=(1200, 800)) panel = wx.panel(self) main_sizer = wx.boxsizer(wx.vertical) self.file_picker = wx.filepickerctrl(panel, wildcard="excel files (*.xlsx)|*.xlsx") self.file_picker.bind(wx.evt_filepicker_changed, self.on_file_selected) main_sizer.add(self.file_picker, 0, wx.all | wx.expand, 10) self.grid = wx.grid.grid(panel) main_sizer.add(self.grid, 1, wx.all | wx.expand, 10) open_button = wx.button(panel, label='open urls in chrome') open_button.bind(wx.evt_button, self.on_open_urls) main_sizer.add(open_button, 0, wx.all | wx.center, 10) panel.setsizer(main_sizer) self.layout() self.show() self.grid_created = false
界面元素:
文件选择器 (self.file_picker):允许用户选择 excel 文件,并绑定 on_file_selected 事件处理函数。当用户选择文件时,该函数将解析并加载数据。
数据网格 (self.grid):这是用于显示 excel 文件数据的表格。wx.grid.grid 是 wxpython 提供的网格控件,允许显示类似 excel 的数据表。
打开 url 按钮 (open_button):该按钮用于批量打开 excel 文件中的 url。当用户点击按钮时,on_open_urls 事件处理函数会处理并打开这些 url。
处理 excel 文件
读取并加载 excel 数据
当用户选择一个 excel 文件时,触发 on_file_selected 事件:
def on_file_selected(self, event): file_path = self.file_picker.getpath() if file_path: try: df = pd.read_excel(file_path, sheet_name='sheet1') expected_columns = [ "blog-list-box href", "course-img src", "blog-list-box-top", "blog-list-content", "article-type", "view-time-box", "view-num", "give-like-num", "comment-num", "comment-num 2", "btn-edit-article href" ] if not all(col in df.columns for col in expected_columns): raise valueerror("excel file does not contain all expected columns") self.update_grid(df) except exception as e: wx.messagebox(f'error reading file: {str(e)}', 'error', wx.ok | wx.icon_error)
- file_path = self.file_picker.getpath():获取用户选择的文件路径。
- pd.read_excel():使用 pandas 从 excel 文件中读取数据。程序假定数据位于名为 'sheet1' 的工作表中。
- expected_columns:指定预期的列名。如果 excel 文件不包含所有这些列,程序会抛出异常并显示错误消息。
更新数据网格
数据成功加载后,通过 update_grid 函数将数据更新到网格中:
def update_grid(self, df): if not self.grid_created: self.grid.creategrid(df.shape[0], df.shape[1]) self.grid_created = true else: current_rows = self.grid.getnumberrows() current_cols = self.grid.getnumbercols() if current_rows < df.shape[0]: self.grid.appendrows(df.shape[0] - current_rows) elif current_rows > df.shape[0]: self.grid.deleterows(0, current_rows - df.shape[0]) if current_cols < df.shape[1]: self.grid.appendcols(df.shape[1] - current_cols) elif current_cols > df.shape[1]: self.grid.deletecols(0, current_cols - df.shape[1]) for i, col in enumerate(df.columns): self.grid.setcollabelvalue(i, str(col)) for j, val in enumerate(df[col]): self.grid.setcellvalue(j, i, str(val)) self.grid.autosizecolumns() self.grid.forcerefresh() self.layout()
该函数根据 excel 文件的行数和列数动态调整网格大小,并逐行逐列填充数据。
批量打开 url
程序从 excel 文件中获取一个名为 "blog-list-box href" 的列,用户可以点击按钮,程序会逐批打开这些 url。每次打开 10 个 url,并询问用户是否继续:
def on_open_urls(self, event): if not os.path.exists(chrome_path): wx.messagebox(f'chrome executable not found at {chrome_path}', 'error', wx.ok | wx.icon_error) return urls = self.get_urls() if not urls: return for i in range(0, len(urls), 10): batch = urls[i:i+10] for url in batch: try: subprocess.popen([chrome_path, url]) except exception as e: wx.messagebox(f'error opening url {url}: {str(e)}', 'error', wx.ok | wx.icon_error) if i + 10 < len(urls): should_continue = wx.messagebox('open next 10 urls?', 'continue', wx.yes_no | wx.icon_question) if should_continue == wx.no: break
核心步骤:
检查 chrome 路径:首先检查 chrome 浏览器是否存在于指定路径中。
获取 url 列表:调用 get_urls 函数,提取网格中的 url 列表。
分批打开 url:使用 subprocess.popen 启动 chrome 并打开这些 url。每次打开 10 个 url,并询问用户是否继续打开下一个 10 个 url。
运行结果
总结
此程序实现了通过 excel 文件进行数据分析,并能够批量打开其中的 url。它结合了 wxpython 用于构建 gui、pandas 用于处理 excel 数据,以及 subprocess 来控制系统程序。程序还包含基本的错误处理和用户交互提示,适合在需要从表格数据中提取和操作 url 的场景下使用。
以上就是使用wxpython和pandas实现xlsx分析器和网页打开器的详细内容,更多关于wxpython pandas xlsx分析器的资料请关注代码网其它相关文章!
发表评论