自动化办公与鼠标键盘模拟

读写 csv 文件

读 csv 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import csv

path = r'./products.csv'


def readCsv(path):
infoList = []
with open(path, 'r', encoding='utf8')as f:
allFileInfo = csv.reader(f)
for row in allFileInfo:
infoList.append(row)
return infoList


readCsv(path)

写 csv 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
import csv

path = r'./000002.csv'


def writeCsv(path, data):
with open(path, 'w', encoding='utf8')as f:
writer = csv.writer(f)
for rowData in data:
writer.writerow(rowData)


writeCsv(path, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])

⚠️注意:会出现空行问题!

读取 PDF 文件

  1. 安装所需的依赖包

    1
    pip install pdfminer3K
  2. 读取 pdf 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    import sys
    import importlib

    importlib.reload(sys)

    from pdfminer.pdfparser import PDFParser, PDFDocument
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
    from pdfminer.converter import PDFPageAggregator
    from pdfminer.layout import LTTextBoxHorizontal, LAParams
    from pdfminer.pdfinterp import PDFTextExtractionNotAllowed

    path = r'./mainDescriptions.pdf'
    toPath = r'./a.txt'


    def readPDF(path, toPath):
    # 以二进制形式打开PDF文件
    f = open(path, 'rb')
    # 创建一个pdf文档分析器
    parser = PDFParser(f)
    # 创建pdf文档
    pdfFile = PDFDocument()
    # 连接分析器与文档
    parser.set_document(pdfFile)
    pdfFile.set_parser(parser)
    # 提供初始化密码
    pdfFile.initialize()
    # 检测文档是否提供txt转换
    if not pdfFile.is_extractable:
    raise PDFTextExtractionNotAllowed
    else:
    # 解析数据
    # 数据管理器
    manager = PDFResourceManager()
    # 创建一个PDF设备对象
    laparams = LAParams()
    device = PDFPageAggregator(manager, laparams=laparams)
    # 创建解释器对象
    interpreter = PDFPageInterpreter(manager, device)
    # 开始循环处理,每次处理一页
    for page in pdfFile.get_pages():
    interpreter.process_page(page)
    # 创建图层
    layout = device.get_result()
    # 处理图层
    for x in layout:
    if (isinstance(x, LTTextBoxHorizontal)):
    with open(toPath, 'a', encoding='utf8')as f:
    str = x.get_text()
    print(str)
    f.write(str + '\n')


    readPDF(path, toPath)

    ⚠️注意:只能处理 PDF 中的文本,图片无法读取。

播放音乐

  1. 安装所需的依赖包

    1
    pip install pygame
  2. 播放音乐

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import time
    import pygame

    filePath = r'./Frida Sundemo-Towers.mp3'

    # 初始化
    pygame.mixer.init()
    # 加载音乐
    track = pygame.mixer.music.load(filePath)
    # 播放
    pygame.mixer.music.play()
    # 暂停一下
    time.sleep(5)
    # 停止
    pygame.mixer.music.stop()

修改背景图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# win+r -> regedit -> HKEY_CURRENT_USER -> Control Panel -> Desktop -> WallPaper

import win32api
import win32con
import win32gui

path = r'E:\图库\壁纸\PC\焰灵姬1.png'


def setWallPaper(path):
# 打开注册表
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, r'Control Panel\Desktop', 0, win32con.KEY_SET_VALUE)
# 修改壁纸样式,2 拉伸、0 居中、6 适应、10 填充
win32api.RegSetValueEx(reg_key, 'WallpaperStyle', '0', win32con.REG_SZ, '2')
# 设置壁纸
# SPIF_SENDWININICHANGE 立即生效
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, win32con.SPIF_SENDWININICHANGE)


setWallPaper(path)

整蛊小程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import time
import pygame

import win32api
import win32con
import win32gui

# 线程模块
import threading


def go():
# 初始化
pygame.mixer.init()
while True:
# 循环播放音乐
for i in range(10):
# 加载音乐
filePath = r'F:\Music' + '\\' + str(i) + '.mp3'
track = pygame.mixer.music.load(filePath)
# 播放
pygame.mixer.music.play()
# 暂停一下
time.sleep(10)
# 停止
pygame.mixer.music.stop()


def setWallPaper(path):
# 打开注册表
reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, r'Control Panel\Desktop', 0, win32con.KEY_SET_VALUE)
# 修改壁纸样式,2 拉伸、0 居中、6 适应、10 填充
win32api.RegSetValueEx(reg_key, 'WallpaperStyle', '0', win32con.REG_SZ, '10')
# 设置壁纸
# SPIF_SENDWININICHANGE 立即生效
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, win32con.SPIF_SENDWININICHANGE)


th = threading.Thread(target=go, name='LoopThread')
th.start()
while True:
for i in range(10):
path = r'F:\Picture' + '\\' + str(i) + '.png'
setWallPaper(path)
time.sleep(10)

键盘模拟

键盘模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import win32con
import win32api
import time

'''
win32api.keybd_event(91, 0, 0, 0)
time.sleep(0.1)
win32api.keybd_event(91, 0, win32con.KEYEVENTF_KEYUP, 0)
'''

for i in range(5):
win32api.keybd_event(91, 0, 0, 0)
time.sleep(0.1)
win32api.keybd_event(77, 0, 0, 0)
time.sleep(0.1)
win32api.keybd_event(77, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(91, 0, win32con.KEYEVENTF_KEYUP, 0)
time.sleep(3)

语音控制游戏

  1. 打开语音识别

  2. 语音控制游戏

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    from win32com.client import constants
    import os
    import win32com.client
    import pythoncom
    import win32con
    import win32api
    import time


    class SpeechRecognition:
    def __init__(self, wordsToAdd):
    self.speaker = win32com.client.Dispatch("SAPI.SpVoice")
    self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer")
    self.context = self.listener.CreateRecoContext()
    self.grammar = self.context.CreateGrammar()
    self.grammar.DictationSetState(0)
    self.wordsRule = self.grammar.Rules.Add("wordsRule", constants.SRATopLevel + constants.SRADynamic, 0)
    self.wordsRule.Clear()
    [self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd]
    self.grammar.Rules.Commit()
    self.grammar.CmdSetRuleState("wordsRule", 1)
    self.grammar.Rules.Commit()
    self.eventHandler = ContextEvents(self.context)
    self.say("Started successfully")

    def say(self, phrase):
    self.speaker.Speak(phrase)


    class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")):
    def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result):
    newResult = win32com.client.Dispatch(Result)
    print("说:", newResult.PhraseInfo.GetText())
    s = newResult.PhraseInfo.GetText()
    if s == "左":
    win32api.keybd_event(37, 0, 0, 0)
    time.sleep(0.1)
    win32api.keybd_event(37, 0, win32con.KEYEVENTF_KEYUP, 0)
    elif s == "上":
    win32api.keybd_event(38, 0, 0, 0)
    time.sleep(0.1)
    win32api.keybd_event(38, 0, win32con.KEYEVENTF_KEYUP, 0)
    elif s == "右":
    win32api.keybd_event(39, 0, 0, 0)
    time.sleep(0.1)
    win32api.keybd_event(39, 0, win32con.KEYEVENTF_KEYUP, 0)
    elif s == "下":
    win32api.keybd_event(40, 0, 0, 0)
    time.sleep(0.1)
    win32api.keybd_event(40, 0, win32con.KEYEVENTF_KEYUP, 0)


    # http://www.3366.com/flash/97506.shtml
    if __name__ == '__main__':
    wordsToAdd = ["上", "下", "左", "右"]
    speechReco = SpeechRecognition(wordsToAdd)
    while True:
    pythoncom.PumpWaitingMessages()

    如果运行代码报错:TypeError: NoneType takes no arguments

    解决方案:https://blog.csdn.net/weixin_37411471/article/details/88363622

鼠标模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import win32con
import win32api
import time

# 设置鼠标的位置
win32api.SetCursorPos([30, 40])
time.sleep(0.1)

# 鼠标左键按下
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0)
# 鼠标左键抬起
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0)

Word 自动化办公

读取 doc 与 docx 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import win32com
import win32com.client


def readWordFile(path):
# 调用系统word功能,可以处理doc和docx两种文件
mw = win32com.client.Dispatch("Word.Application")
# 打开文件
doc = mw.Documents.Open(path)
for paragraph in doc.Paragraphs:
line = paragraph.Range.Text
print(line)
# 关闭文件
doc.Close()
# 退出word
mw.Quit()


path = r'C:\Users\suyin\Desktop\office\01.docx'
readWordFile(path)

读取 doc 与 docx 文件并写入到其他文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import win32com
import win32com.client


def readWordFileToOtherFile(path, toPath):
mw = win32com.client.Dispatch("Word.Application")
doc = mw.Documents.Open(path)

# 将word的数据保存到另一个文件
doc.SaveAs(toPath, 2) # 2表示为txt文件

doc.Close()
mw.Quit()


path = r"C:\Users\suyin\Desktop\office\01.docx"
toPath = r"C:\Users\suyin\Desktop\office\b.txt"
readWordFileToOtherFile(path, toPath)

创建 word 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import win32com
import win32com.client
import os
import time


def makeWordFile(path, name):
word = win32com.client.Dispatch("Word.Application")
# 让文档可见
word.Visible = True

# 创建文档
doc = word.Documents.Add()

# 写内容
# 从头开始写
r = doc.Range(0, 0)
r.InsertAfter("亲爱的" + name + "\n")
r.InsertAfter(" 我想你……\n")

# 存储文件
doc.SaveAs(path)
time.sleep(1)
# 关闭文件
doc.Close()
# 退出word
word.Quit()


names = ["张三", "李四", "王五"]
for name in names:
path = os.path.join(os.getcwd(), name)
print(path)
makeWordFile(path, name)
time.sleep(1)

Excel 自动化办公

读取 xlsx 文件(一张表)

安装所需的依赖包

1
pip install openpyxl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#  xlsx   xls
# openpyxl -> xlsx

from openpyxl.reader.excel import load_workbook


def readXlsxFile(path):
# 打开文件
file = load_workbook(filename=path)
# 所有表格的名称
# print(file.get_sheet_names())
sheets = file.get_sheet_names()
# 拿出一个表格
sheet = file.get_sheet_by_name(sheets[0])
# 最大行数
print(sheet.max_row)
# 最大列数
print(sheet.max_column)
# 表名
print(sheet.title)
# 读取一张表的数据
for lineNum in range(1, sheet.max_row + 1):
# print(lineNum)
lineList = []
for columnNum in range(1, sheet.max_column + 1):
# 拿数据
value = sheet.cell(row=lineNum, column=columnNum).value
# if value != None:
lineList.append(value)

print(lineList)
# exit()


# 不能处理xls文件
path = r"./sunck.xlsx"
readXlsxFile(path)

⚠️注意:不能处理 xls 文件!

返回整体 xlsx 数据(所有表)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#  xlsx   xls
# openpyxl -> xlsx

from openpyxl.reader.excel import load_workbook


def readXlsxFile(path):
dic = {}
file = load_workbook(filename=path)
sheets = file.get_sheet_names()
print(len(sheets))

for sheetName in sheets:
sheet = file.get_sheet_by_name(sheetName)
# 一张表的所有数据
sheetInfo = []
for lineNum in range(1, sheet.max_row + 1):
lineList = []
for columnNum in range(1, sheet.max_column + 1):
value = sheet.cell(row=lineNum, column=columnNum).value
lineList.append(value)
sheetInfo.append(lineList)

# 将一张表的数据存到字典
dic[sheetName] = sheetInfo
return dic


# 不能处理xls文件
path = r"./sunck.xlsx"
dic = readXlsxFile(path)
print(dic["安力博发"])
print(len(dic))

⚠️注意:不能处理 xls 文件!

openpyxl 模块说明

  • Workbook 提供的部分常用属性如下

    属性 含义
    active 获取当前活跃的 Worksheet
    worksheets 以列表的形式返回所有的 sheet 对象(表格对象)
    read_only 判断是否以 read_only 模式打开 Excel 文档
    write_only 判断是否以 write_only 模式打开 Excel 文档
    encoding 获取文档的字符集编码
    properties 获取文档的元数据,如标题,创建者,创建日期等
    sheetnames 以列表的形式返回工作簿中的表的表名(表名字符串)

    openpyxl 库中有个 Workbook 对象,其代表一个 Excel 文档。

  • Workbook 对象提供的部分常用方法如下

    方法 含义
    get_sheet_names 获取所有表格的名称 (新版已经不建议使用,通过 Workbook 的 sheetnames 属性即可获取)
    get_sheet_by_name 通过表格名称获取 Worksheet 对象 (新版也不建议使用,通过 Workbook [‘表名‘] 获取)
    get_active_sheet 获取活跃的表格 (新版建议通过 active 属性获取)
    remove_sheet 删除一个表格
    create_sheet 创建一个空的表格
    copy_worksheet 在 Workbook 内拷贝表格

    openpyxl 库中有个 Workbook 对象,其代表一个 Excel 文档。

  • Worksheet 对象的属性如下

    属性 含义
    title 表格的标题
    dimensions 表格的大小,这里的大小是指含有数据的表格的大小,即:左上角的坐标:右下角的坐标
    max_row 表格的最大行
    min_row 表格的最小行
    max_column 表格的最大列
    min_column 表格的最小列
    rows 按行获取单元格 (Cell 对象) - 生成器
    columns 按列获取单元格 (Cell 对象) - 生成器
    freeze_panes 冻结窗格
    values 按行获取表格的内容 (数据) - 生成器

    Workbook 对象代表一张工作簿,而其中有一张或多张 sheet,这些 sheet 便是一个个 Worksheet 对象。

  • Worksheet 对象的方法如下

    方法 含义
    iter_rows 按行获取所有单元格,内置属性有 (min_row,max_row,min_col,max_col)
    iter_columns 按列获取所有的单元格
    append 在表格末尾添加数据
    merged_cells 合并多个单元格
    unmerged_cells 移除合并的单元格

    Workbook 对象代表一张工作簿,而其中有一张或多张 sheet,这些 sheet 便是一个个 Worksheet 对象。

  • Cell 对象常用的属性如下

    属性 含义
    row 单元格所在的行
    column 单元格坐在的列
    value 单元格的值
    coordinate 单元格的坐标

    对于一张 sheet 表,每一个格子是一个 Cell 对象,其可以用来定位表中任一位置。

返回 xls 和 xlsx 文件内容

安装所需的依赖包

1
2
3
4
5
6
7
pip install xlrd
pip install future
pip install xlwt-future
pip install pyexcel-io
pip install ordereddict
pip install pyexcel
pip install pyexcel-xls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 有序字典
from collections import OrderedDict

# 读取数据
from pyexcel_xls import get_data


def readXlsAndXlsxFile(path):
dic = OrderedDict()
# 读取数据
xdata = get_data(path)
for sheet in xdata:
dic[sheet] = xdata[sheet]
return dic


path = r"./sunck.xls"
dic = readXlsAndXlsxFile(path)
print(dic["安力博发"])
print(len(dic))

写入 xls 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 有序字典
from collections import OrderedDict
# 写入数据
from pyexcel_xls import save_data


def makeExcelFile(path, data):
dic = OrderedDict()
for sheetName, sheetValue in data.items():
d = {}
d[sheetName] = sheetValue
dic.update(d)

save_data(path, dic)


path = r"./b.xls"
makeExcelFile(path, {"表1": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
"表2": [[11, 22, 33], [44, 55, 66], [77, 88, 99]]})

PPT 自动化办公

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import win32com
import win32com.client


def makePPT(path):
ppt = win32com.client.Dispatch("PowerPoint.Application")
ppt.Visible = True

# 增加一个文件
pptFile = ppt.Presentations.Add()

# 创建页 参数1为页数(从1开始) 参数2为类型
page1 = pptFile.Slides.Add(1, 1)
t1 = page1.Shapes[0].TextFrame.TextRange
t1.Text = "嬴政曰"
t2 = page1.Shapes[1].TextFrame.TextRange
t2.Text = "我心中的九十九,应该是法之天下,儒之教化!"

page2 = pptFile.Slides.Add(2, 1)
t3 = page2.Shapes[0].TextFrame.TextRange
t3.Text = "嬴政曰"
t4 = page2.Shapes[1].TextFrame.TextRange
t4.Text = "我欲铸一把天子之剑,以七国为锋,山海为锷,制以五行,开以阴阳,持以春夏,行以秋冬,举世无双,天下归服,为天子之剑!"

page3 = pptFile.Slides.Add(3, 2)
t5 = page3.Shapes[0].TextFrame.TextRange
t5.Text = "韩非曰"
t6 = page3.Shapes[1].TextFrame.TextRange
t6.Text = "尚公子所言深得我心!"

# 保存
pptFile.SaveAs(path)
pptFile.Close()
ppt.Quit()


path = r"C:\Users\suyin\Desktop\office\sunck.ppt"
makePPT(path)

介绍 API 函数的中文帮助文件 提取码:utn6