25 个很棒的 Python 脚本合集(迷你项目) - PDF 下载

在本教程中,我编译了 25 个 Python 程序的集合。我已经包含链接以了解有关每个脚本的更多信息,例如packages installationhow to execute script?

(公众号不能超链接到站外,文末有完整版PDF下载免费赠送)

1.将 JSON 转换为 CSV

import jsonif __name__ == '__main__':    try:        with open('input.json', 'r') as f:            data = json.loads(f.read())
        output = ','.join([*data[0]])        for obj in data:            output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'
        with open('output.csv', 'w') as f:            f.write(output)    except Exception as ex:        print(f'Error: {str(ex)}')

2.密码生成器

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

3.从多个文件中搜索字符串

​​​​​​​

import ostext = input("input text : ")path = input("path : ")# os.chdir(path)def getfiles(path):    f = 0    os.chdir(path)    files = os.listdir()    # print(files)    for file_name in files:        abs_path = os.path.abspath(file_name)        if os.path.isdir(abs_path):            getfiles(abs_path)        if os.path.isfile(abs_path):            f = open(file_name, "r")            if text in f.read():                f = 1                print(text + " found in ")                final_path = os.path.abspath(file_name)                print(final_path)                return True    if f == 1:        print(text + " not found! ")        return False
getfiles(path)

4.从给定网页获取所有链接

import requests as rqfrom bs4 import BeautifulSoup
url = input("Enter Link: ")if ("https" or "http") in url:    data = rq.get(url)else:    data = rq.get("https://" + url)soup = BeautifulSoup(data.text, "html.parser")links = []for link in soup.find_all("a"):    links.append(link.get("href"))
# Writing the output to a file (myLinks.txt) instead of to stdout# You can change 'a' to 'w' to overwrite the file each timewith open("myLinks.txt", 'a') as saved:    print(links[:10], file=saved)

5.图像水印

​​​​​​​

import osfrom PIL import Image
def watermark_photo(input_image_path,watermark_image_path,output_image_path):    base_image = Image.open(input_image_path)    watermark = Image.open(watermark_image_path).convert("RGBA")    # add watermark to your image    position = base_image.size    newsize = (int(position[0]*8/100),int(position[0]*8/100))    # print(position)    watermark = watermark.resize(newsize)    # print(newsize)    # return watermark
    new_position = position[0]-newsize[0]-20,position[1]-newsize[1]-20    # create a new transparent image    transparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))    # paste the original image    transparent.paste(base_image,(0,0))    # paste the watermark image    transparent.paste(watermark,new_position,watermark)    image_mode = base_image.mode    print(image_mode)    if image_mode == 'RGB':        transparent = transparent.convert(image_mode)    else:        transparent = transparent.convert('P')    transparent.save(output_image_path,optimize=True,quality=100)    print("Saving"+output_image_path+"...")
folder = input("Enter Folder Path:")watermark = input("Enter Watermark Path:")os.chdir(folder)files = os.listdir(os.getcwd())print(files)
if not os.path.isdir("output"):    os.mkdir("output")
c = 1for f in files:    if os.path.isfile(os.path.abspath(f)):        if f.endswith(".png") or f.endswith(".jpg"):            watermark_photo(f,watermark,"output/"+f)

6.从WEB页面报废并下载所有图像

from selenium import webdriverimport requests as rqimport osfrom bs4 import BeautifulSoupimport time
# path= E:\web scraping\chromedriver_win32\chromedriver.exepath = input("Enter Path : ")
url = input("Enter URL : ")
output = "output"

def get_url(path, url):    driver = webdriver.Chrome(executable_path=r"{}".format(path))    driver.get(url)    print("loading.....")    res = driver.execute_script("return document.documentElement.outerHTML")
    return res

def get_img_links(res):    soup = BeautifulSoup(res, "lxml")    imglinks = soup.find_all("img", src=True)    return imglinks

def download_img(img_link, index):    try:        extensions = [".jpeg", ".jpg", ".png", ".gif"]        extension = ".jpg"        for exe in extensions:            if img_link.find(exe) > 0:                extension = exe                break
        img_data = rq.get(img_link).content        with open(output + "\\" + str(index + 1) + extension, "wb+") as f:            f.write(img_data)
        f.close()    except Exception:        pass

result = get_url(path, url)time.sleep(60)img_links = get_img_links(result)if not os.path.isdir(output):    os.mkdir(output)
for index, img_link in enumerate(img_links):    img_link = img_link["src"]    print("Downloading...")    if img_link:        download_img(img_link, index)print("Download Complete!!")

7.低电量通知

​​​​​​​

# pip install psutilimport psutil
battery = psutil.sensors_battery()plugged = battery.power_pluggedpercent = battery.percent
if percent <= 30 and plugged!=True:
    # pip install py-notifier    # pip install win10toast    from pynotifier import Notification
    Notification(        title="Battery Low",        description=str(percent) + "% Battery remain!!",        duration=5,  # Duration in seconds
    ).send()

8.计算你的年龄

​​​​​​​

import timefrom calendar import isleap
# judge the leap yeardef judge_leap_year(year):    if isleap(year):        return True    else:        return False

# returns the number of days in each monthdef month_days(month, leap_year):    if month in [1, 3, 5, 7, 8, 10, 12]:        return 31    elif month in [4, 6, 9, 11]:        return 30    elif month == 2 and leap_year:        return 29    elif month == 2 and (not leap_year):        return 28

name = input("input your name: ")age = input("input your age: ")localtime = time.localtime(time.time())
year = int(age)month = year * 12 + localtime.tm_monday = 0
begin_year = int(localtime.tm_year) - yearend_year = begin_year + year
# calculate the daysfor y in range(begin_year, end_year):    if (judge_leap_year(y)):        day = day + 366    else:        day = day + 365
leap_year = judge_leap_year(localtime.tm_year)for m in range(1, localtime.tm_mon):    day = day + month_days(m, leap_year)
day = day + localtime.tm_mdayprint("%s's age is %d years or " % (name, year), end="")print("%d months or %d days" % (month, day))

9.有组织的不同类别的下载文件夹

​​​​​​​

​​​​​​​

import osimport shutilos.chdir("E:\downloads")#print(os.getcwd())
#check number of files in  directoryfiles = os.listdir()
#list of extension (You can add more if you want)extentions = {
      "images": [".jpg", ".png", ".jpeg", ".gif"],    "videos": [".mp4", ".mkv"],    "musics": [".mp3", ".wav"],    "zip": [".zip", ".tgz", ".rar", ".tar"],    "documents": [".pdf", ".docx", ".csv", ".xlsx", ".pptx", ".doc", ".ppt", ".xls"],    "setup": [".msi", ".exe"],    "programs": [".py", ".c", ".cpp", ".p
  • 2
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值