偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

20個Python編程腳本,讓你擁有超能力

開發(fā) 前端
你是否有時看著硬盤突然發(fā)現(xiàn):為什么只剩下100MB空間了?偷偷占用空間多數(shù)就是重復(fù)文件。以下是一個查找并刪除它們的腳本,讓我們釋放你的空間。

當(dāng)你已經(jīng)用Python編程一段時間,或許對StackOverflow也變得熟悉,可能就會想要一些腳本來提升你的編程水平。本文將介紹20個實用的Python腳本,它們不僅能幫你在同事中脫穎而出,還能自動化那些看似不可能的任務(wù),甚至解決你未曾意識到的問題。我們不只討論基本的抓取或HTTP請求,而是更深入的內(nèi)容。讓我們開始探索吧!

目錄

  1. 文件重復(fù)查找器(拯救你的硬盤空間)
  2. 自動整理下載文件夾(拯救文件夾混亂)
  3. 批量調(diào)整圖像大?。ㄖ恍鑾酌?,圖片就好)
  4. 實時天氣通知器(再也不用被雨淋了)
  5. 郵件推送Reddit新帖子(Reddit上癮夢)
  6. 網(wǎng)頁轉(zhuǎn)換電子書(離線訪問必備)
  7. 將文本轉(zhuǎn)換為語音(旁白模式,已激活)
  8. 檢查網(wǎng)站可用性(為網(wǎng)站管理員而生)
  9. 跟蹤加密貨幣價格(因為 HODL)
  10. 下載完成后關(guān)閉你的電腦(因為等待無聊)
  11. 為你的腳本設(shè)置密碼保護(hù)(保持代碼安全)
  12. 監(jiān)控計算機(jī)的CPU使用率(保持冷靜,真的很冷)
  13. 將PDFs轉(zhuǎn)換為文本(為了圖書管理)
  14. 生成二維碼(以便不時之需)
  15. 下載YouTube視頻(再見了,所有的廣告)
  16. 創(chuàng)建隨機(jī)強(qiáng)密碼(別讓密碼太好猜)
  17. 獲取實時股票價格(為投資者而生)
  18. 創(chuàng)建簡單聊天機(jī)器人(你好,再見)
  19. 每日步數(shù)跟蹤(保持健康)
  20. 創(chuàng)建待辦事項列表(生產(chǎn)力是關(guān)鍵)

1. 文件重復(fù)查找器(拯救你的硬盤空間)

你是否有時看著硬盤突然發(fā)現(xiàn):為什么只剩下100MB空間了?偷偷占用空間多數(shù)就是重復(fù)文件。以下是一個查找并刪除它們的腳本,讓我們釋放你的空間。

import os
import hashlib

def hash_file(filename):
    h = hashlib.md5()
    with open(filename, 'rb') as file:
        while chunk := file.read(8192):
            h.update(chunk)
    return h.hexdigest()

def find_duplicates(folder):
    hashes = {}
    for dirpath, _, filenames in os.walk(folder):
        for f in filenames:
            full_path = os.path.join(dirpath, f)
            file_hash = hash_file(full_path)
            if file_hash in hashes:
                print(f"發(fā)現(xiàn)重復(fù)文件: {full_path} == {hashes[file_hash]}")
            else:
                hashes[file_hash] = full_path

find_duplicates('/path/to/your/folder')

提示: 不要在系統(tǒng)文件夾上盲目運行這個腳本,除非你想引入一些混亂。

筆者曾在運行這個腳本后,在不到10分鐘的時間內(nèi)釋放了10GB的空間。

2. 自動整理下載文件夾(拯救文件夾混亂)

我們都知道那種感覺:有一天,你的下載文件夾看起來就像龍卷風(fēng)過后的景象。這里有一個腳本可以整齊地整理一切。

import os
import shutil

def organize_folder(folder):
    file_types = {
        '圖片': ['.jpeg', '.jpg', '.png', '.gif'],
        '視頻': ['.mp4', '.avi', '.mov'],
        '文檔': ['.pdf', '.docx', '.txt'],
        '壓縮包': ['.zip', '.rar']
    }

    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        if os.path.isfile(file_path):
            ext = os.path.splitext(filename)[1].lower()
            for folder_name, extensions in file_types.items():
                if ext in extensions:
                    target_folder = os.path.join(folder, folder_name)
                    os.makedirs(target_folder, exist_ok=True)
                    shutil.move(file_path, os.path.join(target_folder, filename))
                    print(f'將 {filename} 移動到 {folder_name}')

organize_folder('/path/to/Downloads')

3. 批量調(diào)整圖像大?。ㄖ恍鑾酌?,圖片就好)

在處理需要調(diào)整圖像大小的項目嗎?以下是輕松批量調(diào)整圖像大小的方法。

from PIL import Image
import os

def batch_resize(folder, width, height):
    for filename in os.listdir(folder):
        if filename.endswith(('.jpeg', '.jpg', '.png')):
            img = Image.open(os.path.join(folder, filename))
            img = img.resize((width, height))
            img.save(os.path.join(folder, f"resized_{filename}"))
            print(f'調(diào)整了 {filename} 的大小')

batch_resize('/path/to/images', 800, 600)

當(dāng)你的老板希望 "5分鐘內(nèi),我要這些圖片都整整齊齊"的時候,它就是你的最佳選擇。

4. 實時天氣通知器(再也不用被雨淋了)

實時獲取最新天氣預(yù)報,再也不用淋雨大步跑,以下腳本非常好。

import requests
import time

API_KEY = 'your_api_key'
CITY = 'New York'

def get_weather():
    url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}"
    response = requests.get(url)
    data = response.json()
    return data['weather'][0]['description'], data['main']['temp'] - 273.15

while True:
    weather, temp = get_weather()
    print(f"Current weather in {CITY}: {weather}, {temp:.2f}°C")
    time.sleep(3600)  # Run every hour

示例腳本可以獲取紐約氣候,想要獲取本地天氣將url更換至本地天氣預(yù)報網(wǎng)站即可。

5. 郵件推送Reddit新帖子(Reddit上癮夢)

如果你對某個特定的subreddit非常著迷,但又不想經(jīng)常查看,這里有一個 Python 腳本,可以將最新的帖子直接發(fā)送到你的收件箱。

import smtplib
import requests

def send_email(subject, body):
    from_addr = 'your_email@example.com'
    to_addr = 'your_email@example.com'
    msg = f"主題: {subject}\n\n{body}"
    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login('your_email@example.com', 'your_password')
        server.sendmail(from_addr, to_addr, msg)

def get_reddit_posts(subreddit):
    url = f"https://www.reddit.com/r/{subreddit}/new.json"
    headers = {'User-agent': 'Mozilla/5.0'}
    response = requests.get(url, headers=headers)
    data = response.json()
    return [post['data']['title'] for post in data['data']['children']]

posts = get_reddit_posts('python')
send_email('最新 Reddit 帖子', '\n'.join(posts))

有趣的事實: 普通 Reddit 用戶每次訪問網(wǎng)站的平均時間為 16 分鐘。自動化這個過程可以節(jié)省你很多時間。

6.  網(wǎng)頁轉(zhuǎn)換電子書(離線訪問必備)

這個腳本將你喜歡的文章轉(zhuǎn)換為電子書格式,非常適合離線閱讀。

import requests
from bs4 import BeautifulSoup
from ebooklib import epub

def create_ebook(url, book_title):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    
    book = epub.EpubBook()
    book.set_title(book_title)
    
    chapter = epub.EpubHtml(title='章節(jié) 1', file_name='chap_01.xhtml')
    chapter.content = soup.prettify()
    book.add_item(chapter)
    
    book.spine = ['nav', chapter]
    epub.write_epub(f'{book_title}.epub', book, {})

create_ebook('https://example.com/your-favorite-article', '我的電子書')

7. 將文本轉(zhuǎn)換為語音(旁白模式,已激活)

想要傾聽代碼輸出的聲音?這個腳本將打開你的耳朵。

import pyttsx3

def text_to_speech(text):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

text_to_speech('Hello World, Python is amazing!')

提示: 聽輸出可以捕捉錯誤或讓自己從閱讀中解脫出來。

8. 檢查網(wǎng)站可用性(為網(wǎng)站管理員而生)

想知道你的網(wǎng)站是否宕機(jī)?這里有一個簡單的腳本可以為你檢查。

import requests

def is_website_online(url):
    try:
        response = requests.get(url)
        return response.status_code == 200
    except:
        return False

print(is_website_online('https://example.com'))

在某天醒來發(fā)現(xiàn)網(wǎng)站已經(jīng)癱瘓了4個小時之前,你會感謝這個腳本的。

9. 跟蹤加密貨幣價格(因為 HODL)

不要錯過下一個下跌或上漲。使用這個腳本跟蹤你最喜歡的加密貨幣價格。

import requests

def get_crypto_price(crypto):
    url = f"https://api.coindesk.com/v1/bpi/currentprice/{crypto}.json"
    response = requests.get(url)
    data = response.json()
    return data['bpi']['USD']['rate']

print(get_crypto_price('BTC'))

10. 下載完成后關(guān)閉你的電腦(因為等待無聊)

讓你的電腦自己處理。這段腳本在下載完成時關(guān)閉你的電腦

import os
import time

def check_downloads():
    while True:
        if not os.listdir('/path/to/downloads'):
            print("正在關(guān)閉...")
            os.system("shutdown /s /t 1")
        time.sleep(60)

check_downloads()

現(xiàn)在你可以點擊“下載”,走開,等你回來時,電腦已經(jīng)關(guān)機(jī)。

11. 為你的腳本設(shè)置密碼保護(hù)(保持代碼安全)

這里有一個有趣的腳本:給你的腳本設(shè)置密碼保護(hù),以便沒有權(quán)限的人無法運行它們。

import getpass

password = getpass.getpass('輸入你的密碼: ')
if password != 'secret':
    print('訪問被拒絕')
    exit()
else:
    print('訪問授權(quán)')
    # 在這里放置你的受保護(hù)代碼

12. 監(jiān)控CPU使用率(保持冷靜,真的很冷)

用下面的腳本監(jiān)控你的CPU溫度和使用情況。

import psutil

def monitor_cpu():
    print(f"CPU 使用率: {psutil.cpu_percent()}%")
    print(f"內(nèi)存使用率: {psutil.virtual_memory().percent}%")

monitor_cpu()

因為過熱從來都不是一件好事。

13. 將PDFs轉(zhuǎn)換為文本(為了圖書管理)

如果你經(jīng)常處理 PDF,這個腳本會為你提取文本。

import PyPDF2

def pdf_to_text(pdf_file):
    reader = PyPDF2.PdfReader(pdf_file)
    text = ''
    for page in reader.pages:
        text += page.extract_text()
    return text

print(pdf_to_text('example.pdf'))

現(xiàn)在你可以輕松提取重要信息,而不需要無盡的復(fù)制粘貼。

14. 生成二維碼(以便不時之需)

為任何 URL 或文本創(chuàng)建一個二維碼。

import qrcode

def generate_qr(text, filename):
    img = qrcode.make(text)
    img.save(f"{filename}.png")

generate_qr('https://example.com', 'my_qr_code')

誰知道生成二維碼竟然這么簡單?

15. 下載YouTube視頻(再見了,所有廣告)

在幾秒鐘內(nèi)下載你最喜歡的YouTube視頻。

from pytube import YouTube

def download_video(url):
    yt = YouTube(url)
    yt.streams.get_highest_resolution().download()

download_video('https://www.youtube.com/watch?v=your_favorite_video')

請記住不要侵權(quán)下載使用哦。

16. 創(chuàng)建隨機(jī)強(qiáng)密碼(別讓密碼太好猜)

使用這個腳本生成強(qiáng)隨機(jī)密碼。

import string
import random

def generate_password(length):
    chars = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(chars) for _ in range(length))

print(generate_password(16))

請放棄弱密碼的使用。

17. 獲取實時股票價格(為投資者而生)

使用這個快速腳本跟蹤實時股票價格。

import requests

def get_stock_price(symbol):
    url = f"https://finnhub.io/api/v1/quote?symbol={symbol}&token=your_api_key"
    response = requests.get(url)
    data = response.json()
    return data['c']

print(get_stock_price('AAPL'))

在不打開瀏覽器的情況下檢查你的投資組合。

18. 創(chuàng)建簡單聊天機(jī)器人(你好,再見)

制作你自己的聊天機(jī)器人。

import random

def chatbot():
    responses = ['你好!', '我能幫你什么?', '再見!']
    while True:
        user_input = input("你: ")
        if user_input.lower() == 'bye':
            print("聊天機(jī)器人: 再見!")
            break
        print(f"聊天機(jī)器人: {random.choice(responses)}")

chatbot()

僅用幾行代碼創(chuàng)建的個人助手。

19. 每日步數(shù)跟蹤(保持健康)

在Python中獲取你的步數(shù)。

import fitbit

def get_daily_steps(token):
    client = fitbit.Fitbit('client_id', 'client_secret', oauth2_token=token)
    steps = client.activities()['summary']['steps']
    return steps

print(f"今天的步數(shù): {get_daily_steps('your_token')}")

誰說Python不能幫助你保持健康?

20. 創(chuàng)建待辦事項列表(生產(chǎn)力是關(guān)鍵)

一個簡單的待辦事項列表,因為我們都需要一些秩序。

import json

def add_task(task):
    with open('todo.json', 'r+') as file:
        tasks = json.load(file)
        tasks.append(task)
        file.seek(0)
        json.dump(tasks, file)

add_task('發(fā)布 Medium 文章')

以畢達(dá)哥拉斯的方式,保持對事物的關(guān)注。

責(zé)任編輯:武曉燕 來源: Python學(xué)研大本營
相關(guān)推薦

2024-11-26 00:41:23

Python編程腳本

2011-02-22 17:48:34

Konqueror

2015-03-13 11:23:21

編程編程超能力編程能力

2023-11-12 23:01:44

PaddleOCR深度學(xué)習(xí)

2024-08-21 15:20:57

2013-03-11 13:35:26

腕帶

2020-11-03 20:44:35

快手實時隱身技術(shù)隱身超能力

2021-03-11 11:00:38

IBM自動化AI

2019-02-28 22:10:30

AI人工智能預(yù)測

2023-12-22 14:31:52

2021-08-03 21:24:13

ARVR

2024-03-14 08:28:45

2022-03-09 16:19:11

人工智能科技超能力

2013-12-02 10:30:29

瀏覽器

2017-08-22 11:06:22

Android谷歌

2019-03-28 09:26:26

數(shù)據(jù)科學(xué)模型機(jī)器學(xué)習(xí)

2024-05-15 16:07:03

Python框架

2016-12-01 09:32:47

AWS re:InveAWS云計算超能力

2025-06-03 05:00:00

JetpackCompose技巧

2020-08-16 08:30:33

PythonExcel集成
點贊
收藏

51CTO技術(shù)棧公眾號