这些 Python 脚本你一定需要!

本文介绍了几个有趣的Python脚本,包括网速测试、Google搜索结果提取、网络自动化、歌词抓取、图片Exif数据读取、OCR文本识别、图像卡通化、PDF转图片、色彩转换,以及Python学习资源和实战应用

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们每天都会遇到各种各样的编程挑战,解决这些问题需要 Python 基本语法之外的高级编码技术。在本文中,我将介绍一些有趣的 Python 脚本,它们将成为您项目中的宝贵工具。这些解决方案超出了基础知识的范畴,如果您还没有使用过,请考虑将它们添加到您的收藏中,以备将来工作和生活中使用。

使用 Python 进行网速测试

# pip install pyspeedtest
# pip install speedtest
# pip install speedtest-cli

import speedtest
import pyspeedtest

def test_internet_speed():
    # Using speedtest module
    speed_test = speedtest.Speedtest()
    best_server = speed_test.get_best_server()
    print(f"Best server: {best_server['host']} located in {best_server['country']}")

    download_speed = speed_test.download() / 1_000_000  # Convert to Mbps
    print(f"Download speed: {download_speed:.2f} Mbps")

    upload_speed = speed_test.upload() / 1_000_000  # Convert to Mbps
    print(f"Upload speed: {upload_speed:.2f} Mbps")

    # Using pyspeedtest module
    pst = pyspeedtest.SpeedTest()
    ping_speed = pst.ping()
    print(f"Ping speed: {ping_speed} ms")

if __name__ == "__main__":
    test_internet_speed()

该脚本导入了 speedtestpyspeedtest 模块,并定义了 test_internet_speed() 函数来执行速度测试。脚本执行该函数,显示下载速度、上传速度和 ping 的结果,以及测试的最佳服务器信息。

Google 搜索

要执行 Google 搜索并提取重定向 URL,可以使用 “Google” 库。

# pip install google

from googlesearch import search

def extract_redirect_urls(query):
    search_results = search(query, num_results=10, lang="en", stop=10, pause=2.0)
    
    for url in search_results:
        print(url)

if __name__ == "__main__":
    search_query = "Python"
    extract_redirect_urls(search_query)

我们导入 “google” 库,并定义一个名为 extract_redirect_urls(query) 的函数来执行 Google 搜索。该函数将搜索查询作为输入,并从搜索结果中提取前 10 个重定向 URL。然后,我们用 “Python” 示例搜索查询调用该函数,演示其功能。

创建网络机器人

轻松实现网站互动自动化。

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def web_robot():
    # Initialize the Chrome web driver
    bot = webdriver.Chrome("chromedriver.exe")

    # Open Google's homepage
    bot.get('http://www.google.com')

    # Locate the search input field and enter the desired search query
    search = bot.find_element_by_name('q')
    search.send_keys("@Python)

    # Perform the search by hitting the Enter key
    search.send_keys(Keys.RETURN)

    # Wait for the results to load (you can adjust the sleep duration as needed)
    time.sleep(5)

    # Close the web driver
    bot.quit()

if __name__ == "__main__":
    web_robot()

该代码块包含使用 “selenium” 模块设置网络机器人的必要说明。它打开 Google 主页,输入搜索查询"@Python",执行搜索,等待加载结果,最后退出网络驱动程序。你可以扩展和定制这个脚本,以完成各种网络自动化和搜索任务。

从任何歌曲中提取歌词

需要从 Lyricsgenius 网站获取免费 API 密钥。

# pip install lyricsgenius

import lyricsgenius

def get_song_lyrics(api_key, artist_name, song_title):
    genius = lyricsgenius.Genius(api_key)
    artist = genius.search_artist(artist_name, max_songs=5, sort="title")
    song = artist.song(song_title)
    return song.lyrics

if __name__ == "__main__":
    # Replace "xxxxxxxxxxxxxxxxxxxxx" with your actual API key
    api_key = "xxxxxxxxxxxxxxxxxxxxx"
    
    # Replace "Pop Smoke" with the artist's name and "100k On a Coupe" with the song title
    artist_name = "Alan Walker"
    song_title = "Somebody like u"
    
    lyrics = get_song_lyrics(api_key, artist_name, song_title)
    print(lyrics)

我们定义了一个函数 get_song_lyrics(api_key,artist_name,song_title),用于检索任何歌曲的歌词。您需要提供 API 密钥、艺术家姓名和歌曲标题作为该函数的输入。

从任何照片中读取 Exif 数据

方法 1
# pip install pillow

import PIL.Image
import PIL.ExifTags

def get_exif_data_method1(image_path):
    img = PIL.Image.open(image_path)
    exif_data = {
        PIL.ExifTags.TAGS[i]: j
        for i, j in img._getexif().items()
        if i in PIL.ExifTags.TAGS
    }
    return exif_data

if __name__ == "__main__":
    image_path = "Img.jpg"  # Replace this with the actual path of your image
    exif_data = get_exif_data_method1(image_path)
    print(exif_data)
方法 2
# pip install ExifRead

import exifread

def get_exif_data_method2(image_path):
    with open(image_path, 'rb') as file:
        tags = exifread.process_file(file)
    return tags

if __name__ == "__main__":
    image_path = "Img.jpg"  # Replace this with the actual path of your image
    exif_data = get_exif_data_method2(image_path)
    print(exif_data)

我们提供了两种从照片中提取 Exif 数据的方法。方法 1 使用 “Pillow” 模块,而方法 2 使用 “ExifRead” 模块。您需要用图片文件的实际路径替换 “Img.jpg”。然后,脚本将显示指定照片的 Exif 数据。

从图像中提取 OCR 文本

# pip install pytesseract

# Also, download and install the Tesseract OCR engine from Github and set the correct path below.

import pytesseract
from PIL import Image

# Set the path to the Tesseract OCR engine executable
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

def extract_ocr_text(image_path):
    image = Image.open(image_path)
    ocr_text = pytesseract.image_to_string(image, config='')
    return ocr_text

if __name__ == "__main__":
    image_path = "img.png"  # Replace this with the actual path of your image file
    extracted_text = extract_ocr_text(image_path)
    print(extracted_text)

我们使用 “pytesseract” 模块对指定的图像文件执行 OCR。你需要设置 Tesseract OCR 引擎可执行文件的正确路径,将 r'C:\Program Files\Tesseract-OCR\tesseract.exe' 替换为系统中的实际路径。

然后,脚本将从图像中读取文本内容并显示在控制台上。确保安装了必要的依赖项,并正确配置了 Tesseract OCR 引擎,以获得准确的结果。

将照片转换成卡通样式

# pip install opencv-python

import cv2

def convert_to_cartoon(image_path, output_path):
    img = cv2.imread(image_path)
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_img = cv2.medianBlur(gray_img, 5)

    edges = cv2.Laplacian(gray_img, cv2.CV_8U, ksize=5)
    _, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)
    cartooned_img = cv2.bitwise_and(img, img, mask=mask)
    cartooned_img = cv2.medianBlur(cartooned_img, 5)

    cv2.imwrite(output_path, cartooned_img)

if __name__ == "__main__":
    input_image_path = "img.jpg"  # Replace this with the actual path of your input image
    output_image_path = "cartooned.jpg"  # Replace this with the desired output path

    convert_to_cartoon(input_image_path, output_image_path)

我们定义了一个函数 convert_to_cartoon(image_path,output_path),它将输入图像的路径和所需的输出路径作为参数。然后,脚本读取输入图像,对其进行处理以创建卡通化版本,并将结果保存到指定的输出路径中。

要使用该脚本,请将 “img.jpg” 替换为输入图像的实际路径,将 “cartooned.jpg” 替换为保存卡通化图像的所需输出路径。运行脚本将生成输入图像的卡通化版本。

清空回收站

import winshell

def empty_recycle_bin():
    try:
        winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
        print("Recycle bin is now emptied.")
    except:
        print("Recycle bin is already empty.")

if __name__ == "__main__":
    empty_recycle_bin()

函数 empty_recycle_bin() 使用 “winshell” 模块清空回收站。如果操作成功,它会打印一条信息,说明回收站已清空。否则,如果回收站已经清空或在清空过程中出现任何其他错误,则会打印相应的信息。

提高照片质量

# pip install pillow

from PIL import Image, ImageEnhance

def enhance_photo(image_path, enhancement_type, enhancement_factor):
    im = Image.open(image_path)
    
    if enhancement_type == "color":
        enhancer = ImageEnhance.Color(im)
    elif enhancement_type == "contrast":
        enhancer = ImageEnhance.Contrast(im)
    elif enhancement_type == "brightness":
        enhancer = ImageEnhance.Brightness(im)
    elif enhancement_type == "sharpness":
        enhancer = ImageEnhance.Sharpness(im)
    else:
        print("Invalid enhancement type. Choose 'color', 'contrast', 'brightness', or 'sharpness'.")
        return
    
    enhanced_image = enhancer.enhance(enhancement_factor)
    enhanced_image.show("enhanced")

if __name__ == "__main__":
    image_path = "img.jpg"  # Replace this with the actual path of your image file
    
    # Choose your desired enhancement type and factor
    enhancement_type = "brightness"  # Change this to 'color', 'contrast', or 'sharpness'
    enhancement_factor = 1.5  # Adjust this value to control the enhancement intensity
    
    enhance_photo(image_path, enhancement_type, enhancement_factor)

我们创建了一个函数 enhance_photo(),它将图像路径、增强类型(颜色、对比度、亮度或清晰度)和增强因子作为输入。根据所选的增强类型,脚本会使用 Pillow 库的 ImageEnhance 模块对图片进行相应的增强。你可以调整增强因子来控制增强的强度。

要使用该脚本,请将 “img.jpg” 替换为图片的实际路径,然后调整 enhancement_typeenhancement_factor 变量,以实现所需的图片增强效果。

将 PDF 文档的每一页转换成单独的图像

# pip install PyMuPDF

import fitz

def convert_pdf_to_images(pdf_path):
    doc = fitz.open(pdf_path)

    for page in doc:
        pix = page.getPixmap(alpha=False)
        output_filename = f"page-{page.number}.png"
        pix.writePNG(output_filename)

    doc.close()

if __name__ == "__main__":
    pdf_path = 'sample_pdf.pdf'  # Replace this with the actual path of your PDF file
    convert_pdf_to_images(pdf_path)

函数 convert_pdf_to_images(pdf_path) 使用 PyMuPDF 打开 PDF 文件,遍历每一页,并将其转换为 PNG 图像。图像保存的文件名格式为 “page-{page_number}.png”,其中 “{page_number}” 对应页码。

从十六进制转换为 RGB 颜色格式

def hex_to_rgb(hex_value):
    hex_cleaned = hex_value.lstrip('#')
    return tuple(int(hex_cleaned[i:i+2], 16) for i in (0, 2, 4))

if __name__ == "__main__":
    hex_color1 = '#c96d9d'
    hex_color2 = '#fa0515'

    rgb_color1 = hex_to_rgb(hex_color1)
    rgb_color2 = hex_to_rgb(hex_color2)

    print(rgb_color1)  # Output: (201, 109, 157)
    print(rgb_color2)  # Output: (250, 5, 21)

函数 hex_to_rgb(hex_value) 通过从输入的十六进制值中去除 “#” 符号,然后将单个十六进制值转换为相应的十进制值来执行转换。得到的 RGB 值以元组形式返回。

关于Python学习指南

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!

👉Python所有方向的学习路线👈

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取)

在这里插入图片描述

👉Python学习视频600合集👈

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。

在这里插入图片描述

温馨提示:篇幅有限,已打包文件夹,获取方式在:文末

👉Python70个实战练手案例&源码👈

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

在这里插入图片描述

👉Python大厂面试资料👈

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

在这里插入图片描述

👉Python副业兼职路线&方法👈

学好 Python 不论是就业还是做副业赚钱都不错,但要学会兼职接单还是要有一个学习规划。

在这里插入图片描述

👉 这份完整版的Python全套学习资料已经上传,朋友们如果需要可以扫描下方优快云官方认证二维码或者点击链接免费领取保证100%免费

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值