目录
需求分析
由于R语言无法运行,python直接进行偏最小二乘回归无法计算各种指标,Matlab虽然能运行但是效果不好。所以用Excel插件进行运算。但是一直点点点不仅费手费鼠标费时间,我就用python编了个能替我点点点的代码。
环境与基本配置
下载安装Excel插件XLSTAT。该软件可以试用,也可以下载破解版。但试用只能试用14天,且同一个电脑只能试用一次。XLSTAT破解版下载(免积分)https://download.csdn.net/download/weixin_46629224/61093723https://download.csdn.net/download/weixin_46629224/61093723
安装完毕,打开Excel中的XLSTAT插件,点击启动XLSTAT。点击Model——PLS,右击PLS图标,将其添加到快速访问工具栏,以便下一步可以用Alt+4进行键盘操作。
安装Pycharm并配置Python环境。
安装pandas库。Pandas: 强大的 Python 数据分析支持库https://www.pypandas.cn/docs/https://www.pypandas.cn/docs/
安装Welcome to PyAutoGUI’s documentation!https://pyautogui.readthedocs.io/en/latest/https://pyautogui.readthedocs.io/en/latest/PyaotoGUI库。网上很多教程,这里不再赘述。
实现过程
用os库生成文件夹下所以电子表格列表。csv处理前后大小发生很大改变,用下列代码进行文件大小的判断(也可以用pandas库直接打开判断)。
file_stats = os.stat(os.path.join(filepath,csvfile))
if file_stats.st_size>=6000:#if file is proccessed, continue
continue
用pandas库打开csv文件,判断因变量是否可以进行PLS回归。
df = pd.read_csv(os.path.join(filepath, csvfile))
if not 0 < df.WSI.sum() < 99999: # ignore basins where WSI are illegal
continue
用python调用win+R,输入文件名
用alt+4调用PLS插件。这里要提前将选择方式设为列表,并提前选择好,以便于减少批处理操作。
用键盘调用Enter键点击OK。
下一步会有报错或者其他弹窗,用python调用上下左右和Enter键进行选择和点击。
用Alt+F4进行关闭窗口操作,弹出是否保存窗口,python调用Enter键输入OK。
代码实现
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :Calculate_basin
@File :batch_XLSTAT.py
@Author :Ryo
@Date :2021/12/7 10:52 E:\BaiduNetdiskDownload\Driving\Yl_basins\data2\26163.csv
'''
import pyautogui
import time
import os
import pandas as pd
filepath=r'E:\BaiduNetdiskDownload\Driving\Yl_basins\2000_2020'
filelist=os.listdir(filepath)
time.sleep(1)
pyautogui.hotkey('alt', 'esc') #minimize PyCharm
for csvfile in filelist:
try:
file_stats = os.stat(os.path.join(filepath,csvfile))
if file_stats.st_size>=6000:#if file is proccessed, continue
continue
df = pd.read_csv(os.path.join(filepath, csvfile))
if not 0<df.WSI.sum()<99999: #ignore basins where WSI are illegal
continue
print(csvfile)
pyautogui.hotkey('win', 'r')#Open RUN
time.sleep(1)
pyautogui.typewrite(os.path.join(filepath,csvfile))#Type in the file name
time.sleep(1)
pyautogui.press('enter')
time.sleep(4)
pyautogui.hotkey('alt', '4' )
time.sleep(2)
pyautogui.press('enter')#click OK
time.sleep(1)
pyautogui.press('enter')#if select row,press Enter to select
time.sleep(2)
pyautogui.press('right')#click done
time.sleep(2)
pyautogui.press('enter')
time.sleep(3)
pyautogui.hotkey('alt', 'f4')
time.sleep(2)
pyautogui.press('enter')
time.sleep(3)
except Exception as e:
print(csvfile,e)
设计缺陷与注意事项
必须提前打开一个窗口并且将PLS加入到快速访问工具栏,否则会消失。
必须隔一段时间检查一下,因为可能会因为一步出错而跳出程序。
鼠标不能乱动,否则会出错。
进行所有操作之前,Python必须添加Alt+Esc,最小化Pycharm窗口。