5个超实用的Python代码片段

963dade754c3a9b077d47154ab2f5012.png

迷途小书童

读完需要

7

分钟

速读仅需 3 分钟

本篇收集了 5 个常用的 Python 代码片段,非常实用,可以帮助我们更高效的编写代码,实现我们想要实现的功能。

1

   

密码生成器

import random
import string
total = string.ascii_letters + string.digits + string.punctuation
length = 16
password = "".join(random.sample(total, length))
print(password)

这段代码用来生成一个强度较高的随机密码。导入随机数 random 模块和字符串 string 模块,在 total 变量中合并了所有字母、数字和特殊符号,然后设置密码长度 length 为 16 个字符,使用 random.sample 从 total 中随机采样 length 个字符,最后再用 join 拼接成一个字符串,就是生成的密码。

代码的执行结果为

rpI\2bPduJEfz{:~

2

   

低电量通知

import psutil


battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent


if percent <= 30 and plugged!=True:


    from pynotifier import Notification


    Notification(
        title="Battery Low",
        description=str(percent) + "% Battery remain!!",
        duration=5,  # Duration in seconds


    ).send()

这段代码使用 psutil 和 pynotifier 模块实现了一个低电量提醒的桌面通知。导入需要的模块 psutil 和 pynotifier,使用 psutil 获取电池信息,包括是否在充电,还有电量百分比。如果电量<=30%且未插充电器,就使用 pynotifier 发送一个桌面通知 通知标题为 Battery Low,内容为剩余电量百分比,通知显示 5 秒后自动关闭。

3

   

获取网站的 IP 地址和主机名

import socket


def get_hostname_IP():
    hostname = input("Please enter website address(URL):")
    try:
        print (f'Hostname: {hostname}')
        print (f'IP: {socket.gethostbyname(hostname)}')
    except socket.gaierror as error:
        print (f'Invalid Hostname, error raised is {error}')


get_hostname_IP()

这段代码实现了输入网站域名返回对应的 IP 地址的功能。首先,导入 socket 模块,定义 get_hostname_IP 函数,在函数内部,提示输入网址,并用 input 读取用户输入,然后打印输出用户输入的网址(hostname),使用 socket.gethostbyname 根据主机名解析对应的 IP 地址。使用 try except 块捕获可能出现的 socket.gaierror 错误。

代码执行的结果为

Please enter website address(URL):baidu.com
Hostname: baidu.com
IP: 39.156.66.10

4

   

压缩文件夹和文件

import zipfile
import sys
import os




def zip_file(file_path):
    compress_file = zipfile.ZipFile(file_path + '.zip', 'w')
    compress_file.write(path, compress_type=zipfile.ZIP_DEFLATED)
    compress_file.close()




def retrieve_file_paths(dir_name):
    file_paths = []


    for root, directories, files in os.walk(dir_name):
        for filename in files:
            file_path = os.path.join(root, filename)
            file_paths.append(file_path)


    return file_paths




def zip_dir(dir_path, file_paths):
    compress_dir = zipfile.ZipFile(dir_path + '.zip', 'w')
    with compress_dir:
        for file in file_paths:
            compress_dir.write(file)




if __name__ == "__main__":
    path = sys.argv[1]


    if os.path.isdir(path):
        files_path = retrieve_file_paths(path)
        print('The following list of files will be zipped:')
        for file_name in files_path:
            print(file_name)
        zip_dir(path, files_path)
    elif os.path.isfile(path):
        print('The %s will be zipped.' % path)
        zip_file(path)
    else:
        print('a special file(socket,FIFO,device file), please input file or dir')

上述代码实现了一个目录或文件的压缩功能,主要用到了模块 zipfile、os 和 sys。

代码执行的结果为

python test.py input.json
The input.json will be zipped.

5

   

文字转语音

from gtts import gTTS 
import os
file = open("abc.txt", "r").read()


speech = gTTS(text=file, lang='en', slow=False)
speech.save("voice.mp3")
os.system("voice.mp3")

这段代码使用了 gtts 库来将文本转换为语音,并保存为 mp3 文件。gtts 库是Google Text-to-Speech 的缩写,用于将文本转换为语音。使用 gTTS 类创建了一个 speech 对象,将 file 变量中的文本作为参数传递给 text 参数,lang 参数指定了语言,这里是英语(en),slow 参数指定了语音的速度,这里是 False,表示正常速度。

6

   

免费社群

b023506f1b43cc2fcbe5f0a628e535f0.jpeg

76ebbe95dc2f78e92f5b3fc49726cabb.gif

猜你喜欢

转载自blog.csdn.net/djstavaV/article/details/133110016