自动化办公与鼠标键盘模拟
读 csv 文件
1 | import csv |
写 csv 文件
1 | import csv |
⚠️注意:会出现空行问题!
安装所需的依赖包
1
pip install pdfminer3K
读取 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
54import 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
pip install pygame
播放音乐
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import 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 | # win+r -> regedit -> HKEY_CURRENT_USER -> Control Panel -> Desktop -> WallPaper |
1 | import time |
键盘模拟
1 | import win32con |
语音控制游戏
语音控制游戏
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
58from 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 | import win32con |
读取 doc 与 docx 文件
1 | import win32com |
读取 doc 与 docx 文件并写入到其他文件中
1 | import win32com |
创建 word 文件
1 | import win32com |
读取 xlsx 文件(一张表)
安装所需的依赖包
1 | pip install openpyxl |
1 | # xlsx xls |
⚠️注意:不能处理 xls 文件!
返回整体 xlsx 数据(所有表)
1 | # xlsx xls |
⚠️注意:不能处理 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 | pip install xlrd |
1 | # 有序字典 |
写入 xls 文件
1 | # 有序字典 |
1 | import win32com |
介绍 API 函数的中文帮助文件 提取码:utn6