一文分享9個(gè)Python自動(dòng)化辦公提效腳本
1.長(zhǎng)視頻拆分
from subprocess import run
# 拆分文件的路徑
input_video = "test.mp4"
# 10秒分為一個(gè)文件
segment_time = 10
# m3u8文件保存位置
m3u8_list = "/Users/cn-xx/Downloads/Python自動(dòng)化辦公實(shí)戰(zhàn)課/文章5代碼/playlist.m3u8"
# ts文件保存位置
output_video = "/Users/cn-xx/Downloads/Python自動(dòng)化辦公實(shí)戰(zhàn)課/文章5代碼/video-%04d.ts"
cmd1 = ["ffmpeg", "-i", input_video, "-f", "segment", "-segment_time", str(segment_time), "-segment_format",
"mpegts", "-segment_list", m3u8_list, "-c", "copy", "-map", "0", output_video]
run(cmd1)
# 合并
# ffmpeg -allowed_extensions ALL -protocol_whitelist "file,http,crypto,tcp,https" -i index.m3u8 -c copy out.mp4
2.基于感情 色彩進(jìn)行單詞數(shù)量統(tǒng)計(jì)
import jieba
# jieba是第三方庫(kù),需要使用pip3 install jieba 進(jìn)行安裝后使用
#words1="速度快,包裝好,看著特別好,喝著肯定不錯(cuò)!價(jià)廉物美"
words1 = '味道差,口感沒(méi)有,服務(wù)態(tài)度惡劣,心情很差,不再來(lái)了'
words2 = jieba.cut(words1)
words3 = list(words2)
print("/".join(words3))
# 速度/快/,/包裝/好/,/看著/特別/好/,/喝/著/肯定/不錯(cuò)/!/價(jià)廉物美
# words4 停止詞
stop_words = [",", "!"]
words4 =[x for x in words3 if x not in stop_words]
print(words4)
# ['速度', '快', '包裝', '好', '看著', '特別', '好', '喝', '著', '肯定', '不錯(cuò)', '價(jià)廉物美']
# words5 基于詞性移除標(biāo)點(diǎn)符號(hào)
import jieba.posseg as psg
words5 = [ (w.word, w.flag) for w in psg.cut(words1) ]
# 保留形容詞
saved = ['a', 'l']
words5 =[x for x in words5 if x[1] in saved]
print(words5)
# [('快', 'a'), ('好', 'a'), ('好', 'a'), ('不錯(cuò)', 'a'), ('價(jià)廉物美', 'l')]
from snownlp import SnowNLP
words6 = [ x[0] for x in words5 ]
s1 = SnowNLP(" ".join(words3))
print(s1.sentiments)
# 0.99583439264303
positive = 0
negtive = 0
for word in words6:
s2 = SnowNLP(word)
if s2.sentiments > 0.7:
positive+=1
else:
negtive+=1
print(word,str(s2.sentiments))
print(f"正向評(píng)價(jià)數(shù)量:{positive}")
print(f"負(fù)向評(píng)價(jià)數(shù)量:{negtive}")
# 快 0.7164835164835165
# 好 0.6558628208940429
# 好 0.6558628208940429
# 不錯(cuò) 0.8612132352941176
# 價(jià)廉物美 0.7777777777777779
# 正向評(píng)價(jià)數(shù)量:3
# 負(fù)向評(píng)價(jià)數(shù)量:2
3. 批量重命名文件
import os
# 保存圖片的目錄
file_path = "/Users/cn-xx/Downloads/發(fā)票批量下載_20251231154735"
# 需要批量重命名的擴(kuò)展名
old_ext = ".pdf"
# 取得指定文件夾下的文件列表
old_names = os.listdir(file_path)
# 新文件名稱從1開(kāi)始
new_name = 1
# 取得所有的文件名
for old_name in old_names:
# 根據(jù)擴(kuò)展名,判斷文件是否需要改名
if old_name.endswith(old_ext):
# 完整的文件路徑
old_path = os.path.join(file_path, old_name)
# 新的文件名
new_path = os.path.join(file_path, str(new_name)+".pdf")
# 重命名
os.rename(old_path, new_path)
# 文件名數(shù)字加1
new_name = int(new_name)+1
# 顯示改名后的結(jié)果
print(os.listdir(file_path))
# ['3.txt', '2.txt', '1.txt', 'xyz.bmp']
4. 批量打印文件
import os
import subprocess
def batch_print_pdfs():
file_path = "/Users/cn-xx/Downloads/20251231154750"
for filename in os.listdir(file_path):
if filename.lower().endswith('.pdf'):
pdf_file = os.path.join(file_path, filename)
subprocess.run(['lpr', pdf_file])
print(f"已發(fā)送打印: {filename}")
if __name__ == "__main__":
batch_print_pdfs()
5. 快速區(qū)分不同類型的文件
import os
import shutil
from queue import Queue
# 建立新的目錄
def make_new_dir(dir, type_dir):
for td in type_dir:
new_td = os.path.join(dir, td)
if not os.path.isdir(new_td):
os.makedirs(new_td)
# 遍歷目錄并存入隊(duì)列
def write_to_q(path_to_write, q: Queue):
for full_path, dirs, files in os.walk(path_to_write):
# 如果目錄下沒(méi)有文件,就跳過(guò)該目錄
if not files:
continue
else:
q.put(f"{full_path}::{files}")
# 移動(dòng)文件到新的目錄
def move_to_newdir(filename_withext, file_in_path, type_to_newpath):
# 取得文件的擴(kuò)展名
filename_withext = filename_withext.strip(" \'")
ext = filename_withext.split(".")[1]
for new_path in type_to_newpath:
if ext in type_to_newpath[new_path]:
oldfile = os.path.join(file_in_path, filename_withext)
newfile = os.path.join(source_dir, new_path, filename_withext)
shutil.move(oldfile, newfile)
# 將隊(duì)列的文件名分類并寫(xiě)入新的文件夾
def classify_from_q(q: Queue, type_to_classify):
while not q.empty():
item = q.get()
# 將路徑和文件分開(kāi)
filepath, files = item.split("::")
files = files.strip("[]").split(",")
# 對(duì)每個(gè)文件進(jìn)行處理
for filename in files:
# 將文件移動(dòng)到新的目錄
move_to_newdir(filename, filepath, type_to_classify)
if __name__ == "__main__":
# 定義要對(duì)哪個(gè)目錄進(jìn)行文件擴(kuò)展名分類
source_dir = "/Users/cn-xx/Downloads/test"
# 定義文件類型和它的擴(kuò)展名
file_type = {
"music": ("mp3", "wav"),
"movie": ("mp4", "rmvb", "rm", "avi"),
"execute": ("exe", "bat", "dmg", "py", "apk"),
"pic": ("jpg", "png")
}
# 建立新的文件夾
make_new_dir(source_dir, file_type)
# 定義一個(gè)用于記錄擴(kuò)展名放在指定目錄的隊(duì)列
filename_q = Queue()
# 遍歷目錄并存入隊(duì)列
write_to_q(source_dir, filename_q)
# 將隊(duì)列的文件名分類并寫(xiě)入新的文件夾
classify_from_q(filename_q, file_type)
6.如何提取圖片中出現(xiàn)最多的像素
from PIL import Image
# pip3 instlal pillow
# 打開(kāi)圖片文件
image = Image.open("test.JPG")
# 模式“P”為8位彩色圖像,每個(gè)像素用8個(gè)bit表示
image_p = image.convert(
"P", palette=Image.ADAPTIVE
)
# image_p.show()
# 以列表形式返回圖像調(diào)色板,目標(biāo)需先轉(zhuǎn)換為P模式,才具有調(diào)色板屬性,否則得到的調(diào)色板為None
palette = image_p.getpalette()
# 返回此圖像中使用的顏色列表,maxcolors默認(rèn)256
color_counts = sorted(image_p.getcolors(maxcolors=9999), reverse=True)
colors = []
for i in range(5):
palette_index = color_counts[i][1]
dominant_color = palette[palette_index * 3 : palette_index * 3 + 3]
colors.append(tuple(dominant_color))
print(colors)
# [(204, 154, 86), (230, 237, 226), (213, 213, 212), (251, 238, 206), (82, 167, 204)]
for i, val in enumerate(colors):
image.paste(val,(0+i*120, 0 ,100+i*120, 100))
image.save("test2.jpg")
image.show()
Demo :

7.定時(shí)發(fā)郵件
import yagmail
# 163郵箱配置
# 注意:password 需要使用163郵箱的"授權(quán)碼",不是登錄密碼
# 獲取授權(quán)碼:登錄163郵箱 -> 設(shè)置 -> POP3/SMTP/IMAP -> 開(kāi)啟服務(wù) -> 獲取授權(quán)碼
conn = yagmail.SMTP(
user="xx@163.com",
password="xx", # 這里需要改成163郵箱的**授權(quán)碼**
host="smtp.163.com", # 修正:使用 smtp.163.com
port=465
)
content = "自動(dòng)發(fā)送郵件ok"
body = f"模版 {content}"
# 發(fā)送郵件
conn.send("xx@163.com", "主題1", body, "one.png")
8. 把任意文件轉(zhuǎn)換為pdf
使用命令: python3 office_to_pdf.py 輸入表格.xlsx 輸出結(jié)果.pdf
"""
Office文件轉(zhuǎn)PDF通用工具
支持: doc, docx, xls, xlsx, ppt, pptx
"""
import os
import subprocess
import platform
def office_to_pdf(input_file, output_file=None):
"""
將Office文件轉(zhuǎn)換為PDF
參數(shù):
input_file: 輸入文件路徑
output_file: 輸出PDF路徑(可選,默認(rèn)同名.pdf)
返回:
成功返回輸出文件路徑,失敗返回None
"""
if not os.path.exists(input_file):
print(f"錯(cuò)誤: 文件不存在 - {input_file}")
return None
# 獲取文件擴(kuò)展名
_, ext = os.path.splitext(input_file)
ext = ext.lower()
# 支持的格式
supported = ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']
if ext not in supported:
print(f"錯(cuò)誤: 不支持的格式 {ext}")
print(f"支持的格式: {', '.join(supported)}")
return None
# 默認(rèn)輸出文件名
if output_file is None:
output_file = os.path.splitext(input_file)[0] + '.pdf'
# 獲取絕對(duì)路徑
input_file = os.path.abspath(input_file)
output_file = os.path.abspath(output_file)
output_dir = os.path.dirname(output_file)
print(f"轉(zhuǎn)換: {os.path.basename(input_file)} -> {os.path.basename(output_file)}")
# macOS使用soffice (LibreOffice)
if platform.system() == 'Darwin':
return _convert_with_libreoffice(input_file, output_dir, output_file)
else:
print("錯(cuò)誤: 當(dāng)前僅支持macOS系統(tǒng)")
return None
def _convert_with_libreoffice(input_file, output_dir, output_file):
"""使用LibreOffice轉(zhuǎn)換"""
# 檢查L(zhǎng)ibreOffice是否安裝
soffice_paths = [
'/Applications/LibreOffice.app/Contents/MacOS/soffice',
'/usr/local/bin/soffice',
'soffice'
]
soffice = None
for path in soffice_paths:
if os.path.exists(path) or subprocess.run(['which', path],
capture_output=True).returncode == 0:
soffice = path
break
if not soffice:
print("錯(cuò)誤: 未找到LibreOffice")
print("請(qǐng)安裝: brew install --cask libreoffice")
return None
try:
# 使用LibreOffice轉(zhuǎn)換
cmd = [
soffice,
'--headless',
'--convert-to', 'pdf',
'--outdir', output_dir,
input_file
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
# LibreOffice生成的文件名
generated_file = os.path.join(
output_dir,
os.path.splitext(os.path.basename(input_file))[0] + '.pdf'
)
# 如果指定了不同的輸出文件名,重命名
if generated_file != output_file and os.path.exists(generated_file):
os.rename(generated_file, output_file)
if os.path.exists(output_file):
print(f"? 轉(zhuǎn)換成功: {output_file}")
return output_file
else:
print(f"? 轉(zhuǎn)換失敗: 未生成PDF文件")
return None
else:
print(f"? 轉(zhuǎn)換失敗: {result.stderr}")
return None
except subprocess.TimeoutExpired:
print("? 轉(zhuǎn)換超時(shí)")
return None
except Exception as e:
print(f"? 轉(zhuǎn)換出錯(cuò): {e}")
return None
def batch_convert(input_dir, output_dir=None):
"""
批量轉(zhuǎn)換目錄下的所有Office文件
參數(shù):
input_dir: 輸入目錄
output_dir: 輸出目錄(可選,默認(rèn)同輸入目錄)
"""
if output_dir is None:
output_dir = input_dir
os.makedirs(output_dir, exist_ok=True)
supported = ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']
files = [f for f in os.listdir(input_dir)
if os.path.splitext(f)[1].lower() in supported]
if not files:
print(f"未找到Office文件在: {input_dir}")
return
print(f"找到 {len(files)} 個(gè)文件")
print("-" * 60)
success = 0
for filename in files:
input_file = os.path.join(input_dir, filename)
output_file = os.path.join(output_dir,
os.path.splitext(filename)[0] + '.pdf')
if office_to_pdf(input_file, output_file):
success += 1
print()
print("-" * 60)
print(f"完成: {success}/{len(files)} 個(gè)文件轉(zhuǎn)換成功")
if __name__ == "__main__":
import sys
print("Office文件轉(zhuǎn)PDF工具")
print("=" * 60)
print()
# 檢查是否有命令行參數(shù)
if len(sys.argv) > 1:
# 有參數(shù),轉(zhuǎn)換指定文件
input_file = sys.argv[1]
output_file = sys.argv[2] if len(sys.argv) > 2 else None
office_to_pdf(input_file, output_file)
else:
# 無(wú)參數(shù),批量轉(zhuǎn)換當(dāng)前目錄
print("未指定文件,將轉(zhuǎn)換當(dāng)前目錄所有Office文件")
print()
batch_convert('.')
print()
print("用法:")
print(" python3 office_to_pdf.py 文檔.docx")
print(" python3 office_to_pdf.py 表格.xlsx 輸出.pdf")
print(" python3 office_to_pdf.py # 轉(zhuǎn)換當(dāng)前目錄所有文件")
9.pdf逐頁(yè)批量加水印
from PyPDF2 import PdfReader, PdfWriter
def watermark(pdfWithoutWatermark, watermarkfile, pdfWithWatermark):
# 準(zhǔn)備合并后的文件對(duì)象
pdfWriter = PdfWriter()
# 打開(kāi)水印文件
with open(watermarkfile, 'rb') as f:
watermarkpage = PdfReader(f)
# 打開(kāi)需要增加水印的文件
with open(pdfWithoutWatermark, 'rb') as f:
pdf_file = PdfReader(f)
for i in range(len(pdf_file.pages)):
# 從第一頁(yè)開(kāi)始處理
page = pdf_file.pages[i]
# 合并水印和當(dāng)前頁(yè)
page.merge_page(watermarkpage.pages[0])
# 將合并后的PDF文件寫(xiě)入新的文件
pdfWriter.add_page(page)
# 寫(xiě)入新的PDF文件
with open(pdfWithWatermark, "wb") as f:
pdfWriter.write(f)
if __name__ == "__main__":
pdf_without_watermark = "合同.pdf"
pdf_with_watermark = "帶水印合同.pdf"
watermark_file = "水印.pdf"
watermark(pdf_without_watermark, watermark_file, pdf_with_watermark)
print(f"? 水印添加完成:{pdf_with_watermark}")
水印圖:

加水印效果圖:

到此這篇關(guān)于一文分享9個(gè)Python自動(dòng)化辦公提效腳本的文章就介紹到這了,更多相關(guān)Python自動(dòng)化辦公腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pytorch實(shí)現(xiàn)梯度下降和反向傳播圖文詳細(xì)講解
這篇文章主要介紹了pytorch實(shí)現(xiàn)梯度下降和反向傳播,反向傳播的目的是計(jì)算成本函數(shù)C對(duì)網(wǎng)絡(luò)中任意w或b的偏導(dǎo)數(shù)。一旦我們有了這些偏導(dǎo)數(shù),我們將通過(guò)一些常數(shù)α的乘積和該數(shù)量相對(duì)于成本函數(shù)的偏導(dǎo)數(shù)來(lái)更新網(wǎng)絡(luò)中的權(quán)重和偏差2023-04-04
python中l(wèi)ogging模塊的一些簡(jiǎn)單用法的使用
這篇文章主要介紹了python中l(wèi)ogging模塊的一些簡(jiǎn)單用法的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02
python 解決flask uwsgi 獲取不到全局變量的問(wèn)題
今天小編就為大家分享一篇python 解決flask uwsgi 獲取不到全局變量的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
python代碼實(shí)現(xiàn)圖書(shū)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python代碼實(shí)現(xiàn)圖書(shū)管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11
python3.7環(huán)境下安裝Anaconda的教程圖解
這篇文章主要介紹了python3.7環(huán)境下安裝Anaconda的教程,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09

