Python趣味實用小工具

IS1OO 數碼 2

本文將從多個方面對Python趣味實用小工具進行詳細的闡述,介紹實用的小工具應用、技巧以及提高編程能力的方法。

1、工具介紹:隨機密碼生成器,可以自動生成包含大寫字母、小寫字母、數字、符號的密碼。

2、代碼示例:

import random  
import string  
  
def random_password(len):  
    password = []  
    while len > 0:  
        password.append(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation))  
        len -= 1  
    return "".join(password)  
  
print("生成密碼長度為10:", random_password(10))  
print("生成密碼長度為15:", random_password(15))  

3、技巧說明:代碼中使用了random和string模塊,其中random模塊用來生成隨機字符,string模塊則包含所有的大寫字母、小寫字母、數字和標點符號。

1、工具介紹:將圖片轉換成由字符構成的字符畫。

2、代碼示例:

from PIL import Image  
  
# 將RGB值轉換為灰度值  
def rgb2gray(rgb):  
    return int(0.299*rgb[0] + 0.587*rgb[1] + 0.114*rgb[2])  
  
# 將灰度值轉換為字符  
def gray2char(gray):  
    charList = list("WBM@%-+*:. ")  
    charLen = len(charList)  
    unit = 255 // (charLen - 1)  
    return charList[int(gray/unit)]  
    
if __name__ == '__main__':  
    img = Image.open("test.jpg")  
    img = img.resize((160, 90))  
    width, height = img.size  
    txt = ""  
    for y in range(height):  
        for x in range(width):  
            dot = img.getpixel((x, y))  
            txt += gray2char(rgb2gray(dot))  
        txt += "\n"  
    print(txt)  

3、技巧說明:代碼中使用了pillow庫來處理圖片,首先將圖片調整為指定大小,然後對圖片進行灰度處理,最後將灰度轉換成字符。

1、工具介紹:Python有多個畫圖庫,如matplotlib、seaborn等。

2、代碼示例:

import matplotlib.pyplot as plt  
  
x = [1, 2, 3, 4, 5]  
y = [1, 4, 9, 16, 25]  
  
#繪製線性圖  
plt.plot(x, y)  
plt.xlabel('X-axis')  
plt.ylabel('Y-axis')  
plt.title('Linear graph')  
plt.show()  

#繪製散點圖
plt.scatter(x, y)
plt.xlabel('X-axis')  
plt.ylabel('Y-axis')  
plt.title('Scatter plot')  
plt.show() 

3、技巧說明:代碼中使用了matplotlib.pyplot庫來進行數據可視化,其中plot函數可以繪製線性圖,scatter函數可以繪製散點圖。

1、工具介紹:可以對多個文件進行重命名、刪除、拷貝等批量操作。

2、代碼示例:

import os  

path = "./"  
  
# 批量重命名  
def rename():  
    i = 0  
    for file in os.listdir(path):  
        if os.path.isfile(os.path.join(path, file)):  
            # 修改文件名  
            newname = "new_" + str(i) + ".txt"  
            os.rename(os.path.join(path, file), os.path.join(path, newname))  
            i += 1  

# 批量刪除  
def delete():  
    for file in os.listdir(path):  
        if os.path.isfile(os.path.join(path,file)):  
            os.remove(os.path.join(path, file))  

# 批量拷貝  
def copy():  
    for file in os.listdir(path):  
        if os.path.isfile(os.path.join(path, file)):  
            newfile = os.path.join(path, "copy_" + file)  
            # 拷貝文件  
            with open(os.path.join(path, file), "rb") as f1, open(newfile, "wb") as f2:  
                f2.write(f1.read())  
    print("操作完成!")  
    
if __name__ == '__main__':  
    rename()  
    delete()  
    copy()  

3、技巧說明:os模塊用於文件系統操作,通過os.listdir函數可以列出指定文件夾下所有文件,然後可以進行重命名、刪除、拷貝操作。

1、工具介紹:可以提取多個文件的基本信息,如文件名、路徑、大小、創建時間等。

2、代碼示例:

import os  

path = "./"  

# 批量提取文件信息  
def file_info():  
    for file in os.listdir(path):  
        if os.path.isfile(os.path.join(path, file)):  
            file_path = os.path.join(path, file)  
            # 文件名  
            filename = os.path.splitext(file)[0]  
            # 擴展名  
            extname = os.path.splitext(file)[1]  
            # 文件大小  
            size = os.path.getsize(file_path)  
            # 創建時間  
            create_time = os.path.getctime(file_path)  
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(create_time))  
            # 最後修改時間  
            modify_time = os.path.getmtime(file_path)  
            modify_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(modify_time))  
            # 輸出文件信息  
            print("文件名:", filename)  
            print("擴展名:", extname)  
            print("文件大小:", size, "位元組")  
            print("創建時間:", create_time)  
            print("最後修改時間:", modify_time)  
            print("\n")  

if __name__ == '__main__':  
    file_info()  

3、技巧說明:代碼中使用了os模塊和time模塊,os模塊可以獲取文件的基本信息,time模塊可以將時間戳轉換為指定格式的日期時間。

回復

共1條回復 我來回復
  • 暫無回復內容