Python自動化:適合新手練習的五個有趣又實用的Python腳本,幫你快速掌握編程技能!拿走不謝!
實踐永遠是掌握一門技術的最佳方法。本文我將分享5個有趣且實用的Python腳本。新手可以跟著做,這將有助于你將理論應用于實踐,并且幫助你快速掌握Python語法。通過你自己的努力創作出來的東西最后能產生實際作用,你也會有成就感,進一步提升你的興趣和學習的欲望。
好了,話不多說,我們直接開始吧!
恢復模糊的老照片
這個腳本將通過對 PIL、Matplotlib 以及 Numpy 幾個庫的運用,實現模糊老照片的恢復。這只是一個簡單的示例代碼,它執行基本的去噪和銳化操作。當然,在現在這個技術高速發達的時代,有很多便捷的工具可以實現這一目的,并且效果還會更好,比如機器學習和深度學習算法。因此,該腳本只是為了學習實踐的目的。
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
# 加載圖片并將其轉換為灰階圖像
def load_image(image_path):
img = Image.open(image_path)
return img.convert('L')
# 對圖像進行去噪處理
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')
# 對圖像進行銳化處理
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()
圖片
從實現效果來看幾乎沒有什么變化,不要在意結果,我們的目的是掌握實現過程。
以下是實現過程:
- 加載圖像并將其轉換為灰階格式。
- 使用一個簡單的加權平均算法對圖像進行去噪。如果想要更好的結果可以嘗試更復雜的算法。
- 使用反銳化蒙版算法來提升照片的清晰度,突出細節。
- 最后,展示原始和復原圖像。
2. 創建一個簡單的計算器
在這個腳本中,我們將使用Python自帶的圖形開發庫 tkinter 創建一個簡單的計算器,實現基本的加減乘除運算功能。
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 轉圖片
該腳本可以將PDF的所有頁面轉換為圖片(一頁一張圖)。此外,執行該腳本前,請確保已經安裝了 PyMuPDF 庫。如果未安裝,請在終端窗口通過 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 轉 Word 文檔
同樣地,請確保你的環境已安裝了必要的庫 pdf2docx。如果未安裝,通過 pip install pdf2docx 命令安裝即可。下面這個簡單的示例腳本通過 pdf2docx 實現 PDF 轉 Word 文檔。請將輸入和輸出文件路徑替換成你自己的。
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 文件:
圖片
轉換為 Word 文檔:
圖片
如果你細心觀察的話,轉換后,內容格式沒有發生任何變化。Nice!??
代碼實現邏輯:
- 從 pdf2docx 庫導入 Converter 類。
- 定義 convert_pdf_to_word 函數,以輸入 PDF 文件路徑和輸出 DOCX 文件路徑作為參數。
使用輸入 PDF 文件路徑創建一個 PDF 轉換器對象。
調用 convert 方法將 PDF 轉換為 DOCX 格式。
調用 close 方法關閉轉換器以釋放資源。
- 最后在程序入口(__main__)模塊,定義輸入 PDF 文件路徑和輸出 DOCX 文件路徑,然后調用上面定義的 convert_pdf_to_word 函數執行轉換操作。
5. PDF 文件加密/解密
出于安全考慮,你想對你電腦中的PDF文件進行加密處理,但是待加密文件有很多,手動一個個加密的話需要花費很長的時間。這個腳本正好幫你實現批量操作。它使用Python中的 pikepdf
模塊,然后加上一個循環就可以輕松實現文件的批量加密操作。
# 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()
執行上述腳本后,會得到兩個文件,分別以 encryption(加密文件)和 decryption(解密文件)為標志。加密文件打開時會彈出需要輸入文檔打開口令的彈窗:
圖片
而解密文件打開則不需要輸入口令,因為在程序中已經完成解密操作。