Python自動(dòng)化:適合新手練習(xí)的五個(gè)有趣又實(shí)用的Python腳本,幫你快速掌握編程技能!拿走不謝!
實(shí)踐永遠(yuǎn)是掌握一門技術(shù)的最佳方法。本文我將分享5個(gè)有趣且實(shí)用的Python腳本。新手可以跟著做,這將有助于你將理論應(yīng)用于實(shí)踐,并且?guī)椭憧焖僬莆誔ython語法。通過你自己的努力創(chuàng)作出來的東西最后能產(chǎn)生實(shí)際作用,你也會(huì)有成就感,進(jìn)一步提升你的興趣和學(xué)習(xí)的欲望。
好了,話不多說,我們直接開始吧!
恢復(fù)模糊的老照片
這個(gè)腳本將通過對(duì) PIL、Matplotlib 以及 Numpy 幾個(gè)庫的運(yùn)用,實(shí)現(xiàn)模糊老照片的恢復(fù)。這只是一個(gè)簡(jiǎn)單的示例代碼,它執(zhí)行基本的去噪和銳化操作。當(dāng)然,在現(xiàn)在這個(gè)技術(shù)高速發(fā)達(dá)的時(shí)代,有很多便捷的工具可以實(shí)現(xiàn)這一目的,并且效果還會(huì)更好,比如機(jī)器學(xué)習(xí)和深度學(xué)習(xí)算法。因此,該腳本只是為了學(xué)習(xí)實(shí)踐的目的。
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
# 加載圖片并將其轉(zhuǎn)換為灰階圖像
def load_image(image_path):
img = Image.open(image_path)
return img.convert('L')
# 對(duì)圖像進(jìn)行去噪處理
def denoise_image(image, weight=0.1):
img_array = np.asarray(image, dtype=np.float32)
out_array = img_array.copy()
out_array[1:-1, 1:-1] = img_array[1:-1, 1:-1] * (1 - 4 * weight) + \
(img_array[:-2, 1:-1] + img_array[2:, 1:-1] +
img_array[1:-1, :-2] + img_array[1:-1, 2:]) * weight
return Image.fromarray(np.uint8(out_array), 'L')
# 對(duì)圖像進(jìn)行銳化處理
def sharpen_image(image, radius=2, percent=150):
return image.filter(ImageFilter.UnsharpMask(radius=radius, percent=percent, threshold=3))
# 顯示圖片
def display_image(image):
plt.imshow(image, cmap='gray')
plt.axis('off')
plt.show()
# 主程序
def main():
# 替換成你自己的圖像路徑
image_path = r'material_sets/blurred_image.jpg'
# 加載圖像
image = load_image(image_path)
# 圖像去噪
denoised_image = denoise_image(image)
# 圖像銳化
sharpened_image = sharpen_image(denoised_image)
# 顯示原始圖像
print(f'Original image: {display_image(image)}')
# 顯示處理后的圖像
print(f'Processed image: {display_image(sharpened_image)}')
if __name__ == '__main__':
main()
圖片
從實(shí)現(xiàn)效果來看幾乎沒有什么變化,不要在意結(jié)果,我們的目的是掌握實(shí)現(xiàn)過程。
以下是實(shí)現(xiàn)過程:
- 加載圖像并將其轉(zhuǎn)換為灰階格式。
- 使用一個(gè)簡(jiǎn)單的加權(quán)平均算法對(duì)圖像進(jìn)行去噪。如果想要更好的結(jié)果可以嘗試更復(fù)雜的算法。
- 使用反銳化蒙版算法來提升照片的清晰度,突出細(xì)節(jié)。
- 最后,展示原始和復(fù)原圖像。
2. 創(chuàng)建一個(gè)簡(jiǎn)單的計(jì)算器
在這個(gè)腳本中,我們將使用Python自帶的圖形開發(fā)庫 tkinter 創(chuàng)建一個(gè)簡(jiǎn)單的計(jì)算器,實(shí)現(xiàn)基本的加減乘除運(yùn)算功能。
self.resut_value = tk.StringVar()
self.resut_value.set('0')
self.creat_widgets()
def creat_widgets(self):
# Result display
result_entry = tk.Entry(self,
textvariable=self.resut_value,
font=('Arial', 24),
bd=20,
justify='right')
result_entry.grid(row=0, column=0, columnspan=4, sticky='nsew')
# Number buttons
button_font = ('Arial', 14)
button_bg = '#ccc'
button_active_bg = '#aaa'
buttons = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3',
'Clear', '0', 'Delete'
]
row_val = 1
col_val = 0
for button in buttons:
action = lambda x=button: self.on_button_click(x)
tk.Button(self, text=button, font=button_font,
bg=button_bg, activebackground=button_active_bg,
command=action).grid(row=row_val, column=col_val, sticky='nsew')
col_val += 1
if col_val > 2:
col_val = 0
row_val += 1
# Operator buttons
operators = ['+', '-', '*', '/', '=']
for i, operator in enumerate(operators):
action = lambda x=operator: self.on_operator_buttono_click(x)
if operator == '=':
tk.Button(self, text=operator, font=button_font,
bg=button_bg, activebackground=button_active_bg,
command=action).grid(row=i+1, column=0, columnspan=4, sticky='nsew')
else:
tk.Button(self, text=operator, font=button_font,
bg=button_bg, activebackground=button_active_bg,
command=action).grid(row=i+1, column=3, sticky='nsew')
# Configure row and columns to resize with window
for i in range(5):
self.grid_rowconfigure(i, weight=1)
for i in range(4):
self.grid_columnconfigure(i, weight=1)
def on_button_click(self, char):
if char == 'Clear':
self.resut_value.set('0')
elif char == 'Delete':
current_result = self.resut_value.get()
if len(current_result) > 1:
self.resut_value.set(current_result[:-1])
else:
self.resut_value.set('0')
else:
current_result = self.resut_value.get()
if current_result == '0':
self.resut_value.set(char)
else:
self.resut_value.set(current_result + char)
def on_operator_buttono_click(self, operator):
if operator == '=':
self.on_equal_butoon_click()
else:
current_result = self.resut_value.get()
if current_result[-1] in '+-*/':
self.resut_value.set(current_result[-1] + operator)
else:
self.resut_value.set(current_result + operator)
def on_equal_butoon_click(self):
try:
resut = eval(self.resut_value.get())
self.resut_value.set(str(resut))
except ZeroDivisionError:
self.resut_value.set('ZeroDivisionError!')
except Exception as e:
self.resut_value.set('Other Error!')
圖片
3. PDF 轉(zhuǎn)圖片
該腳本可以將PDF的所有頁面轉(zhuǎn)換為圖片(一頁一張圖)。此外,執(zhí)行該腳本前,請(qǐng)確保已經(jīng)安裝了 PyMuPDF 庫。如果未安裝,請(qǐng)?jiān)诮K端窗口通過 pip install PyMuPDF 命令安裝:
import os
import fitz
if __name__ == '__main__':
pdf_path = r'your/path/to/sample.pdf'
doc = fitz.open(pdf_path)
save_path = 'your/path/to/pdf-to-images'
# Making it if the save_path is not exist.
os.makedirs(save_path, exist_ok=True)
for page in doc:
pix = page.get_pixmap(alpha=False)
pix.save(f'{save_path}/{page.number}.png')
print('PDF convert to images successfully!')
4. PDF 轉(zhuǎn) Word 文檔
同樣地,請(qǐng)確保你的環(huán)境已安裝了必要的庫 pdf2docx。如果未安裝,通過 pip install pdf2docx 命令安裝即可。下面這個(gè)簡(jiǎn)單的示例腳本通過 pdf2docx 實(shí)現(xiàn) PDF 轉(zhuǎn) Word 文檔。請(qǐng)將輸入和輸出文件路徑替換成你自己的。
from pdf2docx import Converter
def convert_pdf_to_word(input_pdf, output_docx):
# Create a PDF converter object
pdf_converter = Converter(input_pdf)
# Convret the PDF to a docx file
pdf_converter.convert(output_docx)
# Close the converter to release resources
pdf_converter.close()
if __name__ == '__main__':
input_pdf = r'material_sets/12-SQL-cheat-sheet.pdf'
output_docx = r'material_sets/12-SQL-cheat-sheet.docx'
convert_pdf_to_word(input_pdf, output_docx)
print('The PDF file has been successfully converted to Word format!')
圖片
原 PDF 文件:
圖片
轉(zhuǎn)換為 Word 文檔:
圖片
如果你細(xì)心觀察的話,轉(zhuǎn)換后,內(nèi)容格式?jīng)]有發(fā)生任何變化。Nice!??
代碼實(shí)現(xiàn)邏輯:
- 從 pdf2docx 庫導(dǎo)入 Converter 類。
- 定義 convert_pdf_to_word 函數(shù),以輸入 PDF 文件路徑和輸出 DOCX 文件路徑作為參數(shù)。
使用輸入 PDF 文件路徑創(chuàng)建一個(gè) PDF 轉(zhuǎn)換器對(duì)象。
調(diào)用 convert 方法將 PDF 轉(zhuǎn)換為 DOCX 格式。
調(diào)用 close 方法關(guān)閉轉(zhuǎn)換器以釋放資源。
- 最后在程序入口(__main__)模塊,定義輸入 PDF 文件路徑和輸出 DOCX 文件路徑,然后調(diào)用上面定義的 convert_pdf_to_word 函數(shù)執(zhí)行轉(zhuǎn)換操作。
5. PDF 文件加密/解密
出于安全考慮,你想對(duì)你電腦中的PDF文件進(jìn)行加密處理,但是待加密文件有很多,手動(dòng)一個(gè)個(gè)加密的話需要花費(fèi)很長(zhǎng)的時(shí)間。這個(gè)腳本正好幫你實(shí)現(xiàn)批量操作。它使用Python中的 pikepdf
模塊,然后加上一個(gè)循環(huán)就可以輕松實(shí)現(xiàn)文件的批量加密操作。
# pip install pikepdf
import pikepdf
class PDFEncDecryption:
def __init__(self, file_path, password):
self.file_path = file_path
self.password = password
# PDF encryption
def encryption(self):
pdf = pikepdf.open(self.file_path)
pdf.save(self.file_path.replace('.pdf', '-encryption.pdf'),
encryptinotallow=pikepdf.Encryption(owner=self.password,
user=self.password,
R=4))
pdf.close()
print(f"File {self.file_path.split('/')[-1]} is encrypted successfully!")
# File decryption
def decryption(self):
pdf = pikepdf.open(self.file_path, password=self.password)
pdf.save(self.file_path.replace('-encryption.pdf', '-decryption.pdf'))
pdf.close()
print(f"File {self.file_path.split('/')[-1]} is decrypted successfully!")
if __name__ == '__main__':
file_path = r'material_sets/12-SQL-cheat-sheet.pdf'
# Perform encryption operation
pdfed = PDFEncDecryption(file_path=file_path, password='110110110')
pdfed.encryption()
# Perform decryption operation
file_path2 = r'material_sets/12-SQL-cheat-sheet-encryption.pdf'
pdfed2 = PDFEncDecryption(file_path=file_path2, password='110110110')
pdfed2.decryption()
執(zhí)行上述腳本后,會(huì)得到兩個(gè)文件,分別以 encryption(加密文件)和 decryption(解密文件)為標(biāo)志。加密文件打開時(shí)會(huì)彈出需要輸入文檔打開口令的彈窗:
圖片
而解密文件打開則不需要輸入口令,因?yàn)樵诔绦蛑幸呀?jīng)完成解密操作。