自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

20個(gè)Python編程腳本,讓你擁有超能力

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

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

目錄

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

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

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

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)文件夾上盲目運(yùn)行這個(gè)腳本,除非你想引入一些混亂。

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

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

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

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} 移動(dòng)到 {folder_name}')

organize_folder('/path/to/Downloads')

3. 批量調(diào)整圖像大小(只需幾秒,圖片就好)

在處理需要調(diào)整圖像大小的項(xiàng)目嗎?以下是輕松批量調(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),我要這些圖片都整整齊齊"的時(shí)候,它就是你的最佳選擇。

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

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

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ù)報(bào)網(wǎng)站即可。

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

如果你對(duì)某個(gè)特定的subreddit非常著迷,但又不想經(jīng)常查看,這里有一個(gè) 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))

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

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

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

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', '我的電子書(shū)')

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

想要傾聽(tīng)代碼輸出的聲音?這個(gè)腳本將打開(kāi)你的耳朵。

import pyttsx3

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

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

提示: 聽(tīng)輸出可以捕捉錯(cuò)誤或讓自己從閱讀中解脫出來(lái)。

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

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

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'))

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

9. 跟蹤加密貨幣價(jià)格(因?yàn)?HODL)

不要錯(cuò)過(guò)下一個(gè)下跌或上漲。使用這個(gè)腳本跟蹤你最喜歡的加密貨幣價(jià)格。

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)閉你的電腦(因?yàn)榈却裏o(wú)聊)

讓你的電腦自己處理。這段腳本在下載完成時(shí)關(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)在你可以點(diǎn)擊“下載”,走開(kāi),等你回來(lái)時(shí),電腦已經(jīng)關(guān)機(jī)。

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

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

import getpass

password = getpass.getpass('輸入你的密碼: ')
if password != 'secret':
    print('訪問(wèn)被拒絕')
    exit()
else:
    print('訪問(wèn)授權(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()

因?yàn)檫^(guò)熱從來(lái)都不是一件好事。

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

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

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)在你可以輕松提取重要信息,而不需要無(wú)盡的復(fù)制粘貼。

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

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

import qrcode

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

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

誰(shuí)知道生成二維碼竟然這么簡(jiǎn)單?

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

在幾秒鐘內(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')

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

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

使用這個(gè)腳本生成強(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))

請(qǐng)放棄弱密碼的使用。

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

使用這個(gè)快速腳本跟蹤實(shí)時(shí)股票價(jià)格。

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'))

在不打開(kāi)瀏覽器的情況下檢查你的投資組合。

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

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

import random

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

chatbot()

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

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')}")

誰(shuí)說(shuō)Python不能幫助你保持健康?

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

一個(gè)簡(jiǎn)單的待辦事項(xiàng)列表,因?yàn)槲覀兌夹枰恍┲刃颉?/p>

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á)哥拉斯的方式,保持對(duì)事物的關(guān)注。

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

2024-11-26 00:41:23

Python編程腳本

2015-03-13 11:23:21

編程編程超能力編程能力

2011-02-22 17:48:34

Konqueror

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í)時(shí)隱身技術(shù)隱身超能力

2021-03-11 11:00:38

IBM自動(dòng)化AI

2019-02-28 22:10:30

AI人工智能預(yù)測(cè)

2021-08-03 21:24:13

ARVR

2023-12-22 14:31:52

2022-03-09 16:19:11

人工智能科技超能力

2024-03-14 08:28:45

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庫(kù)框架

2020-08-16 08:30:33

PythonExcel集成

2016-12-01 09:32:47

AWS re:InveAWS云計(jì)算超能力

2019-05-08 14:19:19

貝斯平BespinMSP
點(diǎn)贊
收藏

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