成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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(解密文件)為標志。加密文件打開時會彈出需要輸入文檔打開口令的彈窗:

圖片圖片

而解密文件打開則不需要輸入口令,因為在程序中已經完成解密操作。

責任編輯:武曉燕 來源: 數據派探險家
相關推薦

2024-11-13 13:14:38

2022-10-10 23:19:02

Python腳本語言工具庫

2024-09-24 17:20:16

Python自動化辦公

2022-02-17 13:03:28

Python腳本代碼

2024-11-11 16:55:54

2025-04-02 08:20:00

Python自動化文件管理腳本模板

2022-05-07 14:08:42

Python自動化腳本

2021-11-30 07:01:19

Python自動化腳本

2022-05-07 10:14:07

Python數據可視化

2018-10-18 13:59:36

2024-08-16 21:51:42

2024-06-21 10:46:44

2023-10-26 18:03:14

索引Python技巧

2024-05-13 16:29:56

Python自動化

2020-07-06 10:38:44

辦公軟件工具效率

2024-02-23 18:17:57

Python腳本開發

2024-06-17 10:34:12

2021-03-28 22:55:44

Python編程技術

2023-01-03 08:20:15

2025-02-07 12:58:33

python自動化腳本
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产91在线 | 亚洲 | 国产精品视频网 | 91精品久久久久久久久久入口 | 九九热精品在线视频 | 成人精品一区亚洲午夜久久久 | 久久精品日产第一区二区三区 | 欧美视频一区二区三区 | 亚洲h视频 | 免费国产视频 | 欧美一区二区三区在线观看视频 | 在线视频国产一区 | 日韩精品成人 | 欧美日韩精品综合 | 精品入口麻豆88视频 | 精品国产一区二区三区免费 | 日韩精品一区二区三区视频播放 | 精品欧美一区二区三区久久久 | 亚洲视频一区二区三区 | 粉嫩一区二区三区性色av | 久久久.com| 久久伊人精品 | 久久久999国产精品 中文字幕在线精品 | 在线区| 亚洲第一网站 | 91精品国产综合久久久久久首页 | 日韩欧美久久 | 日韩欧美在线一区 | 夜夜爆操| 狠狠色综合久久丁香婷婷 | 亚洲传媒在线 | 91视频88av| 91精品国产色综合久久不卡98口 | 久久精品国产免费看久久精品 | 7777精品伊人久久精品影视 | 大学生a级毛片免费视频 | 黄色毛片一级 | 亚洲国产91| 免费观看毛片 | 久久新 | 国产精品无码专区在线观看 | 99精品国产一区二区青青牛奶 |