程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Super practical Python code of great God~~~

編輯:Python

The emergence and evolution of programming languages are to directly or succinctly change work efficiency ,Python The emergence of is not only for data analysis 、 machine learning .

If you think about your daily work And life , Some Python Script greatly improves efficiency , At the same time, you can bypass many charging tools , Save a lot of money .

today , Let me introduce some killer scripts written by the great God , It's really a burst of happiness !
author :Jackpop
link :https://www.zhihu.com/question/282627359/answer/2521922355
source : You know
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .

1. image editing (https://jq.qq.com/?_wv=1027&k=UEbz4NcQ)

Use this automated script , Edit your image programmatically . Here are my common functions for editing pictures , As fuzzy 、 rotate 、 Flip 、 Merger, etc . To implement these functions , Always need to install some bloated Software , however , A simple Python Scripts can easily solve .

from PIL import Image
from PIL import ImageDraw
​
# Merge images
img1 = Image.open('img101.jpg')
img2 = Image.open('img102.jpg')
combine = Image.blend(img1, img2, 0.5)
​
# Resize image
resize = Image.open('img101.jpg')
resize = resize.resize((300, 300))
​
# Flipped Picture
flip_image = Image.open('img101.jpg')
flip_image = flip_image.transpose(Image.FLIP_LEFT_RIGHT)
​
# Blur the image
blur_image = Image.open('img101.jpg')
blur_image = blur_image.filter(Image.BLUR)
​
# Add shadow
shadow_image = Image.open('img101.jpg')
shadow_image = shadow_image.filter(Image.EDGE_ENHANCE_MORE)
​
# Cut the picture
crop_image = Image.open('img101.jpg')
crop_image = crop_image.crop((50, 50, 300, 200))
​
# Increase brightness
bright_image = Image.open('img101.jpg')
bright_image = bright_image.point(lambda p: p + 50)
​
# Add text
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))
​
# Rotated image
rotate_image = Image.open('img101.jpg')
rotate_image = rotate_image.rotate(90)
​
# Save image
img1.save('img101.jpg')

2. Audio Editor (https://jq.qq.com/?_wv=1027&k=UEbz4NcQ)

This automated script will edit the audio file for you , You can pick up sound 、 Merge sounds 、 The play 、 Division / Cutting sound, etc , Through this script , Finally we can throw away those paid software .

from pydub import AudioSegment
from pydub.utils import mediainfo
from pydub.playback import play
​
# Extracting sound from video
sound = AudioSegment.from_file("video.mp4", format="mp4")
sound.export("music.mp3", format="mp3")
​
# Get media information
info = mediainfo("musci.wav")
print(info)
​
# Play the audio
play("music.mp3")
​
# Merge audio
sound1 = AudioSegment.from_file("music.mp3")
sound2 = AudioSegment.from_file("music.mp3")
combined = sound1 + sound2
combined.export("music_combined.mp3", format="mp3")
​
# Split audio
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")
​
# Increase or decrease the volume
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_volumn = sound + 10
sound_volumn.export("music_volumn.mp3", format="mp3")
​
# Add mute to audio
sound = AudioSegment.from_file("music.mp3", format="mp3")
sound_silence = sound + AudioSegment.silent(duration=1000)
sound_silence.export("music_silence.mp3", format="mp3")

3. File encryption and decryption (https://jq.qq.com/?_wv=1027&k=UEbz4NcQ)

In the work , We often produce some important documents , It is necessary to limit the number of readers , Then this script can help . This script uses cryptography technology to encrypt your files , When you need to open them , You can decrypt them with a password . This is a very safe way to lock your files , Because you can't read without a key .

​
# Encryption function
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...")
# Decryption function
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. Screen recording tool screen recording

It is a very frequently used tool nowadays , however , At present, many screen recording software charges , Some videos will be watermarked when exporting . therefore , We often see that many people urgently need watermarks 、 Free screen recording software . Actually , One Python The script can handle !

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. from PDF Take the form (https://jq.qq.com/?_wv=1027&k=UEbz4NcQ)

from PDF Extracting tables from is a complex task , adopt OCR The technical effect is generally not ideal , It takes a lot of work to rebuild a table manually . This script will simply start from your PDF Take the form , It's not just You can extract a single PDF Table for , It can also be from multiple PDF Extract the tables one by one .

import camelot
table = camelot.read_pdf('test.pdf', pages='1-2')
​
# Get the total number of tables
print("Total tables: ", table.n)
print(table[0].df)
print(table[1].df)
​
# Export the table as CSV
table[0].to_csv('table1.csv')
table[1].to_csv('table2.csv')
​
# Export the table as Excel
table[0].to_excel('table1.xlsx')
# Export Table to HTML
table[0].to_html('table1.html')
​
# Extract and export tables at once
table.export('tables.csv', f='csv', compress=True)
​
table[0].parse(['Date', 'Description', 'Amount'])

6. Office automation

Have you ever imagined that you can also use Python take MS Office Software automation ?Office Three piece set Word、PPT、Excel It is a tool that most people will use in their work and study , however , At present, many people still handle some repetitive work manually , Very inefficient . This script will free your hands , Realization MS Office Automation .

# Excel automation
import xlrd
wb = xlrd.open_workbook('test.xlsx')
worksheet = wb.sheet_by_index(0)
# By line 、 Column read data
print(worksheet.cell_value(0, 0))
# read whole row
print(worksheet.row_values(0))
​
# Read the entire column
print(worksheet.col_values(1))
​
# write in Excel
worksheet.write(0, 0, 'Hello')
wb.save('test.xlsx')
​
# Word automation
import docx
doc = docx.Document("zen_of_python.docx")
# Read segment by segment
text = [p.text for p in doc.paragraphs]
print(text)
​
# Read table by table
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
​
# write in Word file
doc.add_paragraph("Hello World")
doc.save("test.docx")
​
# PowerPoint automation
from pptx import Presentation
​
# Go through the slides
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)
# write in 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. Picture turn PDF This

Simple automated scripts help you convert your images into PDF Format .

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. Text to speech

It uses Google text to speech API, Convert your text content into the voice of an AI robot .

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. Picture compression

Some websites impose strict limits on the size of images , such as , Some registration websites . Now , You need to use the image compression tool . however , Many compression tools have a great impact on the quality of images . This script compresses your photos to a smaller size with the same quality .

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. Image watermark

This simple script can watermark any image . You can set the text 、 Position and font .

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))

It says 10 A scenario , Are often encountered in daily work and life . Before, most students would choose to seek some cumbersome tools , Even pay , The final effect is not ideal . Through simple Python Script , In fact, it can completely solve our problems , You can also free your hands , Greatly improve efficiency , If you are interested, please try it !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved