10段实用Python代码,帮我省了几万块钱

hello,大家好,我是 Jackpop,硕士毕业于哈尔滨工业大学,曾在华为、阿里等大厂工作,如果你对升学、就业、技术提升等有疑惑,不妨交个朋友:

我是Jackpop,我们交个朋友吧!

编程语言的出现和演进都是为了直接或者简洁的改变工作效率,Python的出现并非只能用于数据分析、机器学习。

如果仔细琢磨日常的工作 和生活,可以通过一些Python脚本大大的提升效率,同时还可以绕开很多收费工具,节省不少钱。

今天,我就来给大家介绍之前写过的一些杀手级脚本,真的是幸福感爆棚!

1. 图像编辑

使用这个自动化脚本,以编程方式编辑你的图像。

下面是我在编辑图片的常用功能,如模糊、旋转、翻转、合并等。

要实现这些功能,往常都需要安装一些臃肿的软件,但是,一个简单的Python脚本就可以轻松解决。

from PIL import Image
from PIL import ImageDraw
​
# 合并图像
img1 = Image.open('img101.jpg')
img2 = Image.open('img102.jpg')
combine = Image.blend(img1, img2, 0.5)# 调整图像大小
resize = Image.open('img101.jpg')
resize = resize.resize((300, 300))# 翻转图像
flip_image = Image.open('img101.jpg')
flip_image = flip_image.transpose(Image.FLIP_LEFT_RIGHT)# 模糊图像
blur_image = Image.open('img101.jpg')
blur_image = blur_image.filter(Image.BLUR)# 添加阴影
shadow_image = Image.open('img101.jpg')
shadow_image = shadow_image.filter(Image.EDGE_ENHANCE_MORE)# 裁剪图片
crop_image = Image.open('img101.jpg')
crop_image = crop_image.crop((50, 50, 300, 200))# 增加亮度
bright_image = Image.open('img101.jpg')
bright_image = bright_image.point(lambda p: p + 50)# 添加文字
text_image = Image.open('img101.jpg')
text_image = text_image.convert('RGB')
draw = ImageDraw.Draw(text_image)
draw.text((10, 10), "Hello World", (255, 255, 255))# 旋转图像
rotate_image = Image.open('img101.jpg')
rotate_image = rotate_image.rotate(90)# 保存图像
img1.save('img101.jpg')

2. 音频编辑

这个自动化脚本将为你编辑音频文件,你可以提取声音、合并声音、播放声音、分割/切割声音等等,通过这个脚本,终于可以扔掉那些付费软件了。

from pydub import AudioSegment
from pydub.utils import mediainfo
from pydub.playback import play
​
# 从视频中提取声音
sound = AudioSegment.from_file("video.mp4", format="mp4")
sound.export("music.mp3", format="mp3")# 获取媒体信息
info = mediainfo("musci.wav")
print(info)# 播放音频
play("music.mp3")# 合并音频
sound1 = AudioSegment.from_file("music.mp3")
sound2 = AudioSegment.from_file("music.mp3")
combined = sound1 + sound2
combined.export("music_combined.mp3", format="mp3")# 分割音频
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_1 = sound[:10000]
sound_2 = sound[10000:]
sound_1.export("music_1.mp3", format="mp3")
sound_2.export("music_2.mp3", format="mp3")# 增大或减小音量
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_volumn = sound + 10
sound_volumn.export("music_volumn.mp3", format="mp3")# 为音频添加静音
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_silence = sound + AudioSegment.silent(duration=1000)
sound_silence.export("music_silence.mp3", format="mp3")

3. 文件加解密

工作中,我们经常会产生一些重要的文件,需要限制阅读人员,那么这个脚本就可以提供帮助。

这个脚本使用密码学技术对你的文件进行加密,当你需要打开它们时,你可以使用密码解密它们。

这是一个非常安全的方法来锁定你的文件,因为在没有钥匙的情况下就没办法阅读。

from cryptography.fernet import Fernet
​
# 加密函数
def Lock_file(file_name, key):
    with open(file_name, 'rb') as file:
        data = file.read()
    f = Fernet(key)
    encrypted_data = f.encrypt(data)
    with open(file_name, 'wb') as file:
        file.write(encrypted_data)
    print("File Lock...")
   
# 解密函数
def Unlock_file(file_name, key):
    with open(file_name, 'rb') as file:
        data = file.read()
    f = Fernet(key)
    decrypted_data = f.decrypt(data)
    with open(file_name, 'wb') as file:
        file.write(decrypted_data)
    print("File Unlock...")
    
key = input("Enter the key: ")
Lock_file('test.txt', key)
Unlock_file('test.txt', key)

4. 录屏工具

录屏是现如今使用非常频繁的一类工具,但是,目前很多录屏软件都收费,有的导出时会在视频上添加水印。

所以,知乎上也经常看到有不少人迫切需求无水印、免费的录屏软件。

其实,一个Python脚本就可以搞定!

import pyautogui
import numpy as np
import cv2
import keyboard
​
def Screen_Recording():
    while True:
        # Press R to Start Recording
        if keyboard.is_pressed('r'):
            print("Recording Has been Started...")
            # resolution
            capture_area = (1920, 1080) 
            
            codec = cv2.VideoWriter_fourcc(*'mp4v')
            filename = "Your_Recording.mp4"
​
            fps = 60.0
            output_video = cv2.VideoWriter(filename, codec, fps, capture_area)
            while True:
                image = pyautogui.screenshot()
                Image_frame = np.array(image)
                Image_frame = cv2.cvtColor(Image_frame, cv2.COLOR_BGR2RGB)
                output_video.write(Image_frame)
                cv2.waitKey(1)
                # Press Q button to Stop recording
                if keyboard.is_pressed('q'):
                    print("Recording Has been Stopped...")
                    break
            output_video.release()
            cv2.destroyAllWindows()
Screen_Recording()

5. 从PDF中提取表格

从PDF中提取表格是一项复杂的任务,通过OCR技术效果一般都不太理想,手动重新建个表格工作量又比较大。

这个脚本将简单地从你的PDF中提取表格,它不仅 可以提取单个PDF的表格,还可以从多个PDF中一个一个地提取表格。

import camelot
table = camelot.read_pdf('test.pdf', pages='1-2')# 获取表的总数
print("Total tables: ", table.n) 
print(table[0].df)
print(table[1].df)# 把表格导出为CSV
table[0].to_csv('table1.csv')
table[1].to_csv('table2.csv')# 把表格导出为Excel
table[0].to_excel('table1.xlsx')
# Export Table to HTML
table[0].to_html('table1.html')# 一次性提取和导出表
table.export('tables.csv', f='csv', compress=True)
​
table[0].parse(['Date', 'Description', 'Amount'])

6. 办公自动化

你是否想象过你也可以用Python将MS Office软件自动化?

Office三件套Word、PPT、Excel是绝大多数人在工作和学习中都会用到的工具,但是,目前很多人还都是手动处理一些重复的工作,效率非常低。

这个脚本就可以解放你的双手,实现MS Office的自动化。

# Excel自动化
import xlrd
wb = xlrd.open_workbook('test.xlsx')
worksheet = wb.sheet_by_index(0)
# 根据行、列读取数据
print(worksheet.cell_value(0, 0))
# read whole row
print(worksheet.row_values(0))# 读取整列
print(worksheet.col_values(1))# 写入Excel
worksheet.write(0, 0, 'Hello')
wb.save('test.xlsx')# Word自动化
import docx
 
doc = docx.Document("zen_of_python.docx")
 
# 逐段读取
text = [p.text for p in doc.paragraphs]
print(text)# 逐表读取
for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            print(cell.text)# 写入Word文档
doc.add_paragraph("Hello World")
doc.save("test.docx")# PowerPoint自动化
from pptx import Presentation
​
# 浏览幻灯片
PP = Presentation('file.pptx')
for slide in PP.slides:
    for shape in slide.shapes:
        for paragraph in shape.text_frame.paragraphs:
            for data in paragraph.runs:
                print(data.text)
# 写入PPT
PP = Presentation()
title_slide_layout = PP.slide_layouts[0]
slide = PP.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = "Medium Article"
PP.save('file.pptx')

7. 图片转PDF

这个简单的自动化脚本帮助你将你的图像转换为PDF格式。

from PIL import Image
def Images_Pdf(filename, output):
    images = []
for file in filename:
        im = Image.open(file)
        im = im.convert('RGB')
        images.append(im)
    
    images[0].save(output, save_all=True, append_images=images[1:])
Images_Pdf(["test1.jpg", "test2.jpg", "test3.jpg"], "output.pdf")

8. 文本转语音

它使用谷歌文本转语音API,将你的文本内容转换为人工智能机器人的声音。

from pygame import mixer
from gtts import gTTS
​
def main():
   tts = gTTS('Like This Article')
   tts.save('output.mp3')
   mixer.init()
   mixer.music.load('output.mp3')
   mixer.music.play()
    
if __name__ == "__main__":
   main()

9. 图片压缩

有些网站会对图片的大小进行严格的限制,比如,一些报考网站。

这时候,就需要用到图片压缩工具。

但是,很多压缩工具对图片的质量影响较大。

这个脚本把你的照片压缩成较小的尺寸而质量不变。

import PIL
from PIL import Image
from tkinter.filedialog import *
fl=askopenfilenames()
img = Image.open(fl[0])
img.save("result.jpg", "JPEG", optimize = True, quality = 10)

10. 图像加水印

这个简单的脚本可以给任何图片加水印。

你可以设置文本、位置和字体。

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def watermark_img(img_path,res_path, text, pos):
    img = Image.open(img_path)
    wm = ImageDraw.Draw(img)
    col= (9, 3, 10)
    wm.text(pos, text, fill=col)
    img.show()
    img.save(res_path)
img = 'initial.jpg'
watermark_img(img, 'result.jpg','IshaanGupta', pos=(1, 0))

上面介绍了10个场景,都是日常工作和生活中经常会遇到的。之前大多数同学都会选择寻求一些繁琐的工具,甚至付费,最终效果也不太理想。

通过简单的Python脚本,其实就可以彻底解决我们的问题,还可以解放双手,大大的提高效率,感兴趣的赶紧试一下吧!

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>