ITPub博客

首页 > 数据库 > 数据库开发技术 > Python自动化:适合新手练习的5个有趣又实用的Python脚本,帮你快速掌握编程技能!拿走不谢!

Python自动化:适合新手练习的5个有趣又实用的Python脚本,帮你快速掌握编程技能!拿走不谢!

原创 数据库开发技术 作者:jackzhang 时间:2024-06-27 06:30:00 0 删除 编辑

实践永远是掌握一门技术的最佳方法。本文我将分享5个有趣且实用的Python脚本。新手可以跟着做,这将有助于你将理论应用于实践,并且帮助你快速掌握Python语法。通过你自己的努力创作出来的东西最后能产生实际作用,你也会有成就感,进一步提升你的兴趣和学习的欲望。

好了,话不多说,我们直接开始吧!

1. 恢复模糊的老照片

这个脚本将通过对 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 创建一个简单的计算器,实现基本的加减乘除运算功能。

import tkinter as tk

class Calculator(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('Simple Calculator')
        self.geometry('500x500')
        
        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!')
            
if __name__ == '__main__':
    app = Calculator()
    app.mainloop()

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'),
                 encryption=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(解密文件)为标志。加密文件打开时会弹出需要输入文档打开口令的弹窗:

而解密文件打开则不需要输入口令,因为在程序中已经完成解密操作。

以上就是今天我要分享的全部内容啦,感谢你的阅读,希望对你有所帮助!


推荐阅读👇👇👇

万字长文:数据科学中 25 个最重要的数学概念(收藏!!!)

神经网络中的梯度累积及其工作原理

Python开发技巧:使用显式打包简化导入

Python OOP 中最常见的 20 种魔术方法

10个Python自动化脚本,简化日常工作任务,看看有没有适合你的!

- END -

🌟 喜欢这篇文章吗?给个赞支持一下吧!🌟

如果你发现今天的内容对你有帮助,不妨点个赞并关注我,第一时间接收更多关于Python、数据分析和机器学习的深入分析和最新趋势。我们一起探索数据的力量,解锁AI的潜能。你的每一次互动都是对我的极大鼓励,也是我们共同成长的动力!

👇👇👇 关注并开启星标提醒,让知识与技能的火花不断在你的职业道路上燃烧吧!

原文作者:数据派探险家;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2017-12-19

  • 博文量
    119
  • 访问量
    55942