当前位置:首页 > 科技  > 软件

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

来源: 责编: 时间:2024-06-27 17:20:34 264观看
导读实践永远是掌握一门技术的最佳方法。本文我将分享5个有趣且实用的Python脚本。新手可以跟着做,这将有助于你将理论应用于实践,并且帮助你快速掌握Python语法。通过你自己的努力创作出来的东西最后能产生实际作用,你也会

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

好了,话不多说,我们直接开始吧!AYS28资讯网——每日最新资讯28at.com

恢复模糊的老照片

这个脚本将通过对 PIL、Matplotlib 以及 Numpy 几个库的运用,实现模糊老照片的恢复。这只是一个简单的示例代码,它执行基本的去噪和锐化操作。当然,在现在这个技术高速发达的时代,有很多便捷的工具可以实现这一目的,并且效果还会更好,比如机器学习和深度学习算法。因此,该脚本只是为了学习实践的目的。AYS28资讯网——每日最新资讯28at.com

import numpy as npimport matplotlib.pyplot as pltfrom 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()

图片图片AYS28资讯网——每日最新资讯28at.com

从实现效果来看几乎没有什么变化,不要在意结果,我们的目的是掌握实现过程。AYS28资讯网——每日最新资讯28at.com

以下是实现过程:AYS28资讯网——每日最新资讯28at.com

  • 加载图像并将其转换为灰阶格式。
  • 使用一个简单的加权平均算法对图像进行去噪。如果想要更好的结果可以尝试更复杂的算法。
  • 使用反锐化蒙版算法来提升照片的清晰度,突出细节。
  • 最后,展示原始和复原图像。

2. 创建一个简单的计算器

在这个脚本中,我们将使用Python自带的图形开发库 tkinter 创建一个简单的计算器,实现基本的加减乘除运算功能。AYS28资讯网——每日最新资讯28at.com

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

图片图片AYS28资讯网——每日最新资讯28at.com

3. PDF 转图片

该脚本可以将PDF的所有页面转换为图片(一页一张图)。此外,执行该脚本前,请确保已经安装了 PyMuPDF 库。如果未安装,请在终端窗口通过 pip install PyMuPDF 命令安装:AYS28资讯网——每日最新资讯28at.com

import osimport fitzif __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 文档。请将输入和输出文件路径替换成你自己的。AYS28资讯网——每日最新资讯28at.com

from pdf2docx import Converterdef 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!')

图片图片AYS28资讯网——每日最新资讯28at.com

原 PDF 文件AYS28资讯网——每日最新资讯28at.com

图片图片AYS28资讯网——每日最新资讯28at.com

转换为 Word 文档AYS28资讯网——每日最新资讯28at.com

图片图片AYS28资讯网——每日最新资讯28at.com

如果你细心观察的话,转换后,内容格式没有发生任何变化。Nice!

本文链接:http://www.28at.com/showinfo-26-96999-0.htmlPython自动化:适合新手练习的五个有趣又实用的Python脚本,帮你快速掌握编程技能!拿走不谢!

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 掌握这四种方法,多线程按序执行不再是问题

下一篇: 高并发场景下到底应该创建多少线程?

标签:
  • 热门焦点
  • Golang 中的 io 包详解:组合接口

    io.ReadWriter// ReadWriter is the interface that groups the basic Read and Write methods.type ReadWriter interface { Reader Writer}是对Reader和Writer接口的组合,
  • 如何正确使用:Has和:Nth-Last-Child

    我们可以用CSS检查,以了解一组元素的数量是否小于或等于一个数字。例如,一个拥有三个或更多子项的grid。你可能会想,为什么需要这样做呢?在某些情况下,一个组件或一个布局可能会
  • 这款新兴工具平台,让你的电脑效率翻倍

    随着信息技术的发展,我们获取信息的渠道越来越多,但是处理信息的效率却成为一个瓶颈。于是各种工具应运而生,都在争相解决我们的工作效率问题。今天我要给大家介绍一款效率
  • 一个注解实现接口幂等,这样才优雅!

    场景码猿慢病云管理系统中其实高并发的场景不是很多,没有必要每个接口都去考虑并发高的场景,比如添加住院患者的这个接口,具体的业务代码就不贴了,业务伪代码如下:图片上述代码有
  • 共享单车的故事讲到哪了?

    来源丨海克财经与共享充电宝相差不多,共享单车已很久没有被国内热点新闻关照到了。除了一再涨价和用户直呼用不起了。近日多家媒体再发报道称,成都、天津、郑州等地多个共享单
  • 本地生活这块肥肉,拼多多也想吃一口

    出品/壹览商业 作者/李彦编辑/木鱼拼多多也看上本地生活这块蛋糕了。近期,拼多多在App首页“充值中心”入口上线了本机生活界面。壹览商业发现,该界面目前主要
  • 信通院:小米、华为等11家应用商店基本完成APP签名及验签工作

    中国信通院表示,目前,小米、华为、OPPO、vivo、360手机助手、百度手机助手、应用宝、豌豆荚和努比亚等9家应用商店,以及抖音和快手2家新型应用分发平
  • 三星Galaxy Z Fold/Flip 5国行售价曝光 :最低7499元/12999元起

    据官方此前宣布,三星将于7月26日也就是明天在韩国首尔举办Unpacked活动,届时将带来带来包括Galaxy Buds 3、Galaxy Watch 6、Galaxy Tab S9、Galaxy
  • 首发天玑9200+ iQOO Neo8系列发布首销售价2299元起

    2023年5月23日晚,iQOO Neo8系列正式发布。其中,Neo系列首款Pro之作——iQOO Neo8 Pro强悍登场,限时售价3099元起;价位段最强性能手机iQOO Neo8同期上市
Top