23个很棒的Python脚本集合分享(迷你项目)

目录
  • 1.将 JSON 转换为 CSV
  • 2.密码生成器
  • 3.从多个文件中搜索字符串
  • 4.从给定网页获取所有链接
  • 5.图像水印
  • 6.从网页抓取并下载所有图片
  • 7.低电量通知
  • 8.计算您的年龄
  • 9.组织不同类别的下载文件夹
  • 10.从CSV文件批量发送电子邮件
  • 11.获取网站的IP地址和主机名
  • 12.终端进度条
  • 13.无线密码弹出器
  • 14.给定网站的快照
  • 15.将文件拆分为块
  • 16.加密和解密文本
  • 17.定期捕获屏幕截图
  • 18.十进制到二进制转换器
  • 19.CLI 待办事项应用程序
  • 20.货币转换器
  • 21.制作一个简单的秒表
  • 22.用于压缩文件夹和文件的Python脚本
  • 23.文字转语音

1.将 JSON 转换为 CSV

import json
if __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 random
import string
total = string.ascii_letters + string.digits + string.punctuation
length = 16
password = "".join(random.sample(total, length))
print(password)

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

import os
text = 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 rq
from 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"))

# 将输出写入文件(myLinks.txt)而不是stdout
# 每次都可以将“a”更改为“w”以覆盖文件
with open("myLinks.txt", 'a') as saved:
    print(links[:10], file=saved)

5.图像水印

import os
from 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")
    # 为图像添加水印
    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
    # 创建新的透明图像
    transparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))
    # 粘贴原始图像
    transparent.paste(base_image,(0,0))
    # 粘贴水印图像
    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 = 1
for 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.从网页抓取并下载所有图片

from selenium import webdriver
import requests as rq
import os
from bs4 import BeautifulSoup
import time

# path= E:\web scraping\chromedriver_win32\chromedriver.exe
path = 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 psutil
import psutil

battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = 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,  # 持续时间(秒)

    ).send()

8.计算您的年龄

import time
from calendar import isleap

# 判断闰年
def judge_leap_year(year):
    if isleap(year):
        return True
    else:
        return False

# 返回每个月的天数
def 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_mon
day = 0

begin_year = int(localtime.tm_year) - year
end_year = begin_year + year

# 计算天数
for 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_mday
print("%s's age is %d years or " % (name, year), end="")
print("%d months or %d days" % (month, day))

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

import os
import shutil
os.chdir("E:\downloads")
#print(os.getcwd())

#检查目录中的文件数
files = os.listdir()

#扩展名列表(如果需要,可以添加更多)
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", ".php", ".C", ".CPP"],
    "design": [".xd", ".psd"]

}

#根据扩展名排序到特定文件夹
def sorting(file):
    keys = list(extentions.keys())
    for key in keys:
        for ext in extentions[key]:
            # print(ext)
            if file.endswith(ext):
                return key

#遍历每个文件
for file in files:
    dist = sorting(file)
    if dist:
        try:
            shutil.move(file, "../download-sorting/" + dist)
        except:
            print(file + " is already exist")
    else:
        try:
            shutil.move(file, "../download-sorting/others")
        except:
            print(file + " is already exist")

10.从CSV文件批量发送电子邮件

import csv
from email.message import EmailMessage
import smtplib

def get_credentials(filepath):
    with open("credentials.txt", "r") as f:
        email_address = f.readline()
        email_pass = f.readline()
    return (email_address, email_pass)

def login(email_address, email_pass, s):
    s.ehlo()
    # 启动TLS以实现安全
    s.starttls()
    s.ehlo()
    # Authentication
    s.login(email_address, email_pass)
    print("login")

def send_mail():
    s = smtplib.SMTP("smtp.gmail.com", 587)
    email_address, email_pass = get_credentials("./credentials.txt")
    login(email_address, email_pass, s)

    # 要发送的消息
    subject = "Welcome to Python"
    body = """Python is an interpreted, high-level,
    general-purpose programming language.\n
    Created by Guido van Rossum and first released in 1991,
    Python's design philosophy emphasizes code readability\n
    with its notable use of significant whitespace"""

    message = EmailMessage()
    message.set_content(body)
    message['Subject'] = subject

    with open("emails.csv", newline="") as csvfile:
        spamreader = csv.reader(csvfile, delimiter=" ", quotechar="|")
        for email in spamreader:
            s.send_message(email_address, email[0], message)
            print("Send To " + email[0])

    # 终止会话
    s.quit()
    print("sent")

if __name__ == "__main__":
    send_mail()

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

# 获取网站的IP地址和主机名
# importing socket library
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()

12.终端进度条

from tqdm import tqdm
from PIL import Image
import os
from time import sleep

def Resize_image(size, image):
    if os.path.isfile(image):
        try:
            im = Image.open(image)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save("resize/" + str(image) + ".jpg")
        except Exception as ex:
            print(f"Error: {str(ex)} to {image}")

path = input("Enter Path to images : ")
size = input("Size Height , Width : ")
size = tuple(map(int, size.split(",")))

os.chdir(path)

list_images = os.listdir(path)
if "resize" not in list_images:
    os.mkdir("resize")

for image in tqdm(list_images, desc="Resizing Images"):
    Resize_image(size, image)
    sleep(0.1)
print("Resizing Completed!")

13.无线密码弹出器

import subprocess

data = (
    subprocess.check_output(["netsh", "wlan", "show", "profiles"])
    .decode("utf-8")
    .split("\n")
)
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
for i in profiles:
    results = (
        subprocess
        .check_output(["netsh", "wlan", "show", "profile", i, "key=clear"])
        .decode("utf-8")
        .split("\n")
    )
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    try:
        print("{:<30}|  {:<}".format(i, results[0]))
    except IndexError:
        print("{:<30}|  {:<}".format(i, ""))

14.给定网站的快照

import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary

script_name = sys.argv[0]

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

try:
    url = sys.argv[1]

    driver.get(url)
    page_width = driver.execute_script('return document.body.scrollWidth')
    page_height = driver.execute_script('return document.body.scrollHeight')
    driver.set_window_size(page_width, page_height)
    driver.save_screenshot('screenshot.png')
    driver.quit()
    print("SUCCESS")

except IndexError:
    print('Usage: %s URL' % script_name)

15.将文件拆分为块

import sys
import os
import shutil
import pandas as pd

class Split_Files:
    '''
        Class file for split file program
    '''
    def __init__(self, filename, split_number):
        '''
            Getting the file name and the split index
            Initializing the output directory, if present then truncate it.
            Getting the file extension
        '''
        self.file_name = filename
        self.directory = "file_split"
        self.split = int(split_number)
        if os.path.exists(self.directory):
            shutil.rmtree(self.directory)
        os.mkdir(self.directory)
        if self.file_name.endswith('.txt'):
            self.file_extension = '.txt'
        else:
            self.file_extension = '.csv'
        self.file_number = 1

    def split_data(self):
        '''
            spliting the input csv/txt file according to the index provided
        '''
        data = pd.read_csv(self.file_name, header=None)
        data.index += 1

        split_frame = pd.DataFrame()
        output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}"

        for i in range(1, len(data)+1):
            split_frame = split_frame.append(data.iloc[i-1])
            if i % self.split == 0:
                output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}"
                if self.file_extension == '.txt':
                    split_frame.to_csv(output_file, header=False, index=False, sep=' ')
                else:
                    split_frame.to_csv(output_file, header=False, index=False)
                split_frame.drop(split_frame.index, inplace=True)
                self.file_number += 1
        if not split_frame.empty:
            output_file = f"{self.directory}/split_file{self.file_number}{self.file_extension}"
            split_frame.to_csv(output_file, header=False, index=False)

if __name__ == '__main__':
    file, split_number = sys.argv[1], sys.argv[2]
    sp = Split_Files(file, split_number)
    sp.split_data()

16.加密和解密文本

from Crypto.Cipher import AES
from Crypto import Random
from binascii import b2a_hex
import sys

# 获取明文
plain_text = sys.argv[1]

# 密钥长度必须为16(AES-128)、24(AES-192)或32(AES-256)字节。
key = b'this is a 16 key'

# 生成长度等于AES块大小的不可重复密钥向量
iv = Random.new().read(AES.block_size)

# 使用 key 和 iv 初始化 AES 对象,使用 MODE_CFB 模式
mycipher = AES.new(key, AES.MODE_CFB, iv)

# 将iv(密钥向量)添加到加密密文的开头并一起传输
ciphertext = iv + mycipher.encrypt(plain_text.encode())

# 要解密,请使用key和iv生成新的AES对象
mydecrypt = AES.new(key, AES.MODE_CFB, ciphertext[:16])

# 使用新生成的AES对象解密加密的密文
decrypttext = mydecrypt.decrypt(ciphertext[16:])

file_out = open("encrypted.bin", "wb")
file_out.write(ciphertext[16:])
file_out.close()

print("The key k is: ", key)
print("iv is: ", b2a_hex(ciphertext)[:16])
print("The encrypted data is: ", b2a_hex(ciphertext)[16:])
print("The decrypted data is: ", decrypttext.decode())

17.定期捕获屏幕截图

import os
import argparse
import pyautogui
import time

parser = argparse.ArgumentParser()

parser.add_argument("-p", "--path", help="absolute path to store screenshot.", default=r"./images")
parser.add_argument("-t", "--type", help="h (in hour) or m (in minutes) or s (in seconds)", default='h')
parser.add_argument("-f", "--frequency", help="frequency for taking screenshot per h/m/s.", default=1, type=int)

args = parser.parse_args()

sec = 0.

if args.type == 'h':
    sec = 60 * 60 / args.frequency
elif args.type == 'm':
    sec = 60 / args.frequency

if sec < 1.:
    sec = 1.

if os.path.isdir(args.path) != True:
    os.mkdir(args.path)

try:
    while True:
        t = time.localtime()
        current_time = time.strftime("%H_%M_%S", t)
        file = current_time + ".jpg"
        image = pyautogui.screenshot(os.path.join(args.path,file))
        print(f"{file} saved successfully.\n")
        time.sleep(sec)

except KeyboardInterrupt:
    print("End of script by user interrupt")

18.十进制到二进制转换器

try:
    menu = int(input("Choose an option: \n 1. Decimal to binary \n 2. Binary to decimal\n Option: "))
    if menu < 1 or menu > 2:
        raise ValueError
    if menu == 1:
        dec = int(input("Input your decimal number:\nDecimal: "))
        print("Binary: {}".format(bin(dec)[2:]))
    elif menu == 2:
        binary = input("Input your binary number:\n Binary: ")
        print("Decimal: {}".format(int(binary, 2)))
except ValueError:
    print ("please choose a valid option")

19.CLI 待办事项应用程序

import click

@click.group()
@click.pass_context
def todo(ctx):
    '''Simple CLI Todo App'''
    ctx.ensure_object(dict)
    # 打开todo.txt – 第一行包含最新的ID,其余包含任务和ID
    with open('./todo.txt') as f:
        content = f.readlines()
    # 从 todo.txt 传输数据到 context
    ctx.obj['LATEST'] = int(content[:1][0])
    ctx.obj['TASKS'] = {en.split('```

')[0]:en.split('

```')[1][:-1] for en in content[1:]}

@todo.command()
@click.pass_context
def tasks(ctx):
    '''Display tasks'''
    if ctx.obj['TASKS']:
        click.echo('YOUR TASKS\n**********')
        # 遍历 context 中存储的所有任务
        for i, task in ctx.obj['TASKS'].items():
            click.echo('• ' + task + ' (ID: ' + i + ')')
        click.echo('')
    else:
        click.echo('No tasks yet! Use ADD to add one.\n')

@todo.command()
@click.pass_context
@click.option('-add', '--add_task', prompt='Enter task to add')
def add(ctx, add_task):
    '''Add a task'''
    if add_task:
        #Add task to list in context
        ctx.obj['TASKS'][ctx.obj['LATEST']] = add_task
        click.echo('Added task "' + add_task + '" with ID ' + str(ctx.obj['LATEST']))
        # 打开todo.txt and write current index and tasks with IDs (separated by " ```
{% endraw %}
 ")
        curr_ind = [str(ctx.obj['LATEST'] + 1)]
        tasks = [str(i) + '
{% raw %}
```' + t for (i, t) in ctx.obj['TASKS'].items()]
        with open('./todo.txt', 'w') as f:
            f.writelines(['%s\n' % en for en in curr_ind + tasks])

@todo.command()
@click.pass_context
@click.option('-fin', '--fin_taskid', prompt='Enter ID of task to finish', type=int)
def done(ctx, fin_taskid):
    '''Delete a task by ID'''
    # 查找具有关联ID的任务
    if str(fin_taskid) in ctx.obj['TASKS'].keys():
        task = ctx.obj['TASKS'][str(fin_taskid)]
        # 从上下文中的任务列表中删除任务
        del ctx.obj['TASKS'][str(fin_taskid)]
        click.echo('Finished and removed task "' + task + '" with id ' + str(fin_taskid))
        # 打开todo.txt and 使用ID写入当前索引和任务 (separated by " ```
{% endraw %}
 ")
        if ctx.obj['TASKS']:
            curr_ind = [str(ctx.obj['LATEST'] + 1)]
            tasks = [str(i) + '
{% raw %}
```' + t for (i, t) in ctx.obj['TASKS'].items()]
            with open('./todo.txt', 'w') as f:
                f.writelines(['%s\n' % en for en in curr_ind + tasks])
        else:
            # 如果列表为空,则将ID跟踪器重置为0
            with open('./todo.txt', 'w') as f:
                f.writelines([str(0) + '\n'])
    else:
        click.echo('Error: no task with id ' + str(fin_taskid))

if __name__ == '__main__':
    todo()

20.货币转换器

import requests
import json
import sys
from pprint import pprint

url = "http://data.fixer.io/api/latest?access_key=33ec7c73f8a4eb6b9b5b5f95118b2275"
data = requests.get(url).text
data2 = json.loads(data) #带来请求是否成功、时间戳等
fx = data2["rates"]

currencies = [
    "AED : Emirati Dirham,United Arab Emirates Dirham",
    "AFN : Afghan Afghani,Afghanistan Afghani",
    "ALL : Albanian Lek,Albania Lek",
    "AMD : Armenian Dram,Armenia Dram",
    "ANG : Dutch Guilder,Netherlands Antilles Guilder,Bonaire,Curaçao,Saba,Sint Eustatius,Sint Maarten",
    "AOA : Angolan Kwanza,Angola Kwanza",
    "ARS : Argentine Peso,Argentina Peso,Islas Malvinas",
    "AUD : Australian Dollar,Australia Dollar,Christmas Island,Cocos (Keeling) Islands,Norfolk Island,Ashmore and Cartier Islands,Australian Antarctic Territory,Coral Sea Islands,Heard Island,McDonald Islands,Kiribati,Nauru",
    "AWG : Aruban or Dutch Guilder,Aruba Guilder",
    "AZN : Azerbaijan Manat,Azerbaijan Manat",
    "BAM : Bosnian Convertible Mark,Bosnia and Herzegovina Convertible Mark",
    "BBD : Barbadian or Bajan Dollar,Barbados Dollar",
    "BDT : Bangladeshi Taka,Bangladesh Taka",
    "BGN : Bulgarian Lev,Bulgaria Lev",
    "BHD : Bahraini Dinar,Bahrain Dinar",
    "BIF : Burundian Franc,Burundi Franc",
    "BMD : Bermudian Dollar,Bermuda Dollar",
    "BND : Bruneian Dollar,Brunei Darussalam Dollar",
    "BOB : Bolivian Bolíviano,Bolivia Bolíviano",
    "BRL : Brazilian Real,Brazil Real",
    "BSD : Bahamian Dollar,Bahamas Dollar",
    "BTC : Bitcoin,BTC, XBT",
    "BTN : Bhutanese Ngultrum,Bhutan Ngultrum",
    "BWP : Botswana Pula,Botswana Pula",
    "BYN : Belarusian Ruble,Belarus Ruble",
    "BYR : Belarusian Ruble,Belarus Ruble",
    "BZD : Belizean Dollar,Belize Dollar",
    "CAD : Canadian Dollar,Canada Dollar",
    "CDF : Congolese Franc,Congo/Kinshasa Franc",
    "CHF : Swiss Franc,Switzerland Franc,Liechtenstein,Campione d'Italia,Büsingen am Hochrhein",
    "CLF : Chilean Unit of Account",
    "CLP : Chilean Peso,Chile Peso",
    "CNY : Chinese Yuan Renminbi,China Yuan Renminbi",
    "COP : Colombian Peso,Colombia Peso",
    "CRC : Costa Rican Colon,Costa Rica Colon",
    "CUC : Cuban Convertible Peso,Cuba Convertible Peso",
    "CUP : Cuban Peso,Cuba Peso",
    "CVE : Cape Verdean Escudo,Cape Verde Escudo",
    "CZK : Czech Koruna,Czech Republic Koruna",
    "DJF : Djiboutian Franc,Djibouti Franc",
    "DKK : Danish Krone,Denmark Krone,Faroe Islands,Greenland",
    "DOP : Dominican Peso,Dominican Republic Peso",
    "DZD : Algerian Dinar,Algeria Dinar",
    "EGP : Egyptian Pound,Egypt Pound,Gaza Strip",
    "ERN : Eritrean Nakfa,Eritrea Nakfa",
    "ETB : Ethiopian Birr,Ethiopia Birr,Eritrea",
    "EUR : Euro,Euro Member Countries,Andorra,Austria,Azores,Baleares (Balearic Islands),Belgium,Canary Islands,Cyprus,Finland,France,French Guiana,French Southern Territories,Germany,Greece,Guadeloupe,Holland (Netherlands),Holy See (Vatican City),Ireland (Eire),Italy,Luxembourg,Madeira Islands,Malta,Monaco,Montenegro,Netherlands",
    "FJD : Fijian Dollar,Fiji Dollar",
    "FKP : Falkland Island Pound,Falkland Islands (Malvinas) Pound",
    "GBP : British Pound,United Kingdom Pound,United Kingdom (UK),England,Northern Ireland,Scotland,Wales,Falkland Islands,Gibraltar,Guernsey,Isle of Man,Jersey,Saint Helena and Ascension,South Georgia and the South Sandwich Islands,Tristan da Cunha",
    "GEL : Georgian Lari,Georgia Lari",
    "GGP : Guernsey Pound,Guernsey Pound",
    "GHS : Ghanaian Cedi,Ghana Cedi",
    "GIP : Gibraltar Pound,Gibraltar Pound",
    "GMD : Gambian Dalasi,Gambia Dalasi",
    "GNF : Guinean Franc,Guinea Franc",
    "GTQ : Guatemalan Quetzal,Guatemala Quetzal",
    "GYD : Guyanese Dollar,Guyana Dollar",
    "HKD : Hong Kong Dollar,Hong Kong Dollar",
    "HNL : Honduran Lempira,Honduras Lempira",
    "HRK : Croatian Kuna,Croatia Kuna",
    "HTG : Haitian Gourde,Haiti Gourde",
    "HUF : Hungarian Forint,Hungary Forint",
    "IDR : Indonesian Rupiah,Indonesia Rupiah,East Timor",
    "ILS : Israeli Shekel,Israel Shekel,Palestinian Territories",
    "IMP : Isle of Man Pound,Isle of Man Pound",
    "INR : Indian Rupee,India Rupee,Bhutan,Nepal",
    "IQD : Iraqi Dinar,Iraq Dinar",
    "IRR : Iranian Rial,Iran Rial",
    "ISK : Icelandic Krona,Iceland Krona",
    "JEP : Jersey Pound,Jersey Pound",
    "JMD : Jamaican Dollar,Jamaica Dollar",
    "JOD : Jordanian Dinar,Jordan Dinar",
    "JPY : Japanese Yen,Japan Yen",
    "KES : Kenyan Shilling,Kenya Shilling",
    "KGS : Kyrgyzstani Som,Kyrgyzstan Som",
    "KHR : Cambodian Riel,Cambodia Riel",
    "KMF : Comorian Franc,Comorian Franc",
    "KPW : North Korean Won,Korea (North) Won",
    "KRW : South Korean Won,Korea (South) Won",
    "KWD : Kuwaiti Dinar,Kuwait Dinar",
    "KYD : Caymanian Dollar,Cayman Islands Dollar",
    "KZT : Kazakhstani Tenge,Kazakhstan Tenge",
    "LAK : Lao Kip,Laos Kip",
    "LBP : Lebanese Pound,Lebanon Pound",
    "LKR : Sri Lankan Rupee,Sri Lanka Rupee",
    "LRD : Liberian Dollar,Liberia Dollar",
    "LSL : Basotho Loti,Lesotho Loti",
    "LTL : Lithuanian litas",
    "LVL : Latvia Lats",
    "LYD : Libyan Dinar,Libya Dinar",
    "MAD : Moroccan Dirham,Morocco Dirham,Western Sahara",
    "MDL : Moldovan Leu,Moldova Leu",
    "MGA : Malagasy Ariary,Madagascar Ariary",
    "MKD : Macedonian Denar,Macedonia Denar",
    "MMK : Burmese Kyat,Myanmar (Burma) Kyat",
    "MNT : Mongolian Tughrik,Mongolia Tughrik",
    "MOP : Macau Pataca,Macau Pataca",
    "MRU : Mauritanian Ouguiya,Mauritania Ouguiya",
    "MUR : Mauritian Rupee,Mauritius Rupee",
    "MVR : Maldivian Rufiyaa,Maldives (Maldive Islands) Rufiyaa",
    "MWK : Malawian Kwacha,Malawi Kwacha",
    "MXN : Mexican Peso,Mexico Peso",
    "MYR : Malaysian Ringgit,Malaysia Ringgit",
    "MZN : Mozambican Metical,Mozambique Metical",
    "NAD : Namibian Dollar,Namibia Dollar",
    "NGN : Nigerian Naira,Nigeria Naira",
    "NIO : Nicaraguan Cordoba,Nicaragua Cordoba",
    "NOK : Norwegian Krone,Norway Krone,Bouvet Island,Svalbard,Jan Mayen,Queen Maud Land,Peter I Island",
    "NPR : Nepalese Rupee,Nepal Rupee,India (unofficially near India-Nepal border)",
    "NZD : New Zealand Dollar,New Zealand Dollar,Cook Islands,Niue,Pitcairn Islands,Tokelau",
    "OMR : Omani Rial,Oman Rial",
    "PAB : Panamanian Balboa,Panama Balboa",
    "PEN : Peruvian Sol,Peru Sol",
    "PGK : Papua New Guinean Kina,Papua New Guinea Kina",
    "PHP : Philippine Peso,Philippines Peso",
    "PKR : Pakistani Rupee,Pakistan Rupee",
    "PLN : Polish Zloty,Poland Zloty",
    "PYG : Paraguayan Guarani,Paraguay Guarani",
    "QAR : Qatari Riyal,Qatar Riyal",
    "RON : Romanian Leu,Romania Leu",
    "RSD : Serbian Dinar,Serbia Dinar",
    "RUB : Russian Ruble,Russia Ruble,Tajikistan,Abkhazia,South Ossetia",
    "RWF : Rwandan Franc,Rwanda Franc",
    "SAR : Saudi Arabian Riyal,Saudi Arabia Riyal",
    "SBD : Solomon Islander Dollar,Solomon Islands Dollar",
    "SCR : Seychellois Rupee,Seychelles Rupee",
    "SDG : Sudanese Pound,Sudan Pound",
    "SEK : Swedish Krona,Sweden Krona",
    "SGD : Singapore Dollar,Singapore Dollar",
    "SHP : Saint Helenian Pound,Saint Helena Pound",
    "SLL : Sierra Leonean Leone,Sierra Leone Leone",
    "SOS : Somali Shilling,Somalia Shilling",
    "SRD : Surinamese Dollar,Suriname Dollar",
    "STN : Sao Tomean Dobra,São Tomé and Príncipe Dobra",
    "SVC : Salvadoran Colon,El Salvador Colon",
    "SYP : Syrian Pound,Syria Pound",
    "SZL : Swazi Lilangeni,eSwatini Lilangeni",
    "THB : Thai Baht,Thailand Baht",
    "TJS : Tajikistani Somoni,Tajikistan Somoni",
    "TMT : Turkmenistani Manat,Turkmenistan Manat",
    "TND : Tunisian Dinar,Tunisia Dinar",
    "TOP : Tongan Pa'anga,Tonga Pa'anga",
    "TRY : Turkish Lira,Turkey Lira,North Cyprus",
    "TTD : Trinidadian Dollar,Trinidad and Tobago Dollar,Trinidad,Tobago",
    "TWD : Taiwan New Dollar,Taiwan New Dollar",
    "TZS : Tanzanian Shilling,Tanzania Shilling",
    "UAH : Ukrainian Hryvnia,Ukraine Hryvnia",
    "UGX : Ugandan Shilling,Uganda Shilling",
    "USD : US Dollar,United States Dollar,America,American Samoa,American Virgin Islands,British Indian Ocean Territory,British Virgin Islands,Ecuador,El Salvador,Guam,Haiti,Micronesia,Northern Mariana Islands,Palau,Panama,Puerto Rico,Turks and Caicos Islands,United States Minor Outlying Islands,Wake Island,East Timor",
    "UYU : Uruguayan Peso,Uruguay Peso",
    "UZS : Uzbekistani Som,Uzbekistan Som",
    "VEF : Venezuelan Bolívar,Venezuela Bolívar",
    "VND : Vietnamese Dong,Viet Nam Dong",
    "VUV : Ni-Vanuatu Vatu,Vanuatu Vatu",
    "WST : Samoan Tala,Samoa Tala",
    "XAF : Central African CFA Franc BEAC,Communauté Financière Africaine (BEAC) CFA Franc BEAC,Cameroon,Central African Republic,Chad,Congo/Brazzaville,Equatorial Guinea,Gabon",
    "XAG : Silver Ounce,Silver",
    "XAU : Gold Ounce,Gold",
    "XCD : East Caribbean Dollar,East Caribbean Dollar,Anguilla,Antigua and Barbuda,Dominica,Grenada,The Grenadines and Saint Vincent,Montserrat",
    "XDR : IMF Special Drawing Rights,International Monetary Fund (IMF) Special Drawing Rights",
    "XOF : CFA Franc,Communauté Financière Africaine (BCEAO) Franc,Benin,Burkina Faso,Ivory Coast,Guinea-Bissau,Mali,Niger,Senegal,Togo",
    "XPF : CFP Franc,Comptoirs Français du Pacifique (CFP) Franc,French Polynesia,New Caledonia,Wallis and Futuna Islands",
    "YER : Yemeni Rial,Yemen Rial",
    "ZAR : South African Rand,South Africa Rand,Lesotho,Namibia",
    "ZMK : Zambian Kwacha,Zambia Kwacha",
    "ZMW : Zambian Kwacha,Zambia Kwacha",
    "ZWL : Zimbabwean Dollar,Zimbabwe Dollar",
]

# 以下函数计算实际转换
def function1():
    query = input(
        "Please specify the amount of currency to convert, from currency, to currency (with space in between).\nPress SHOW to see list of currencies available. \nPress Q to quit. \n"
    )
    if query == "Q":
        sys.exit()
    elif query == "SHOW":
        pprint(currencies)
        function1()
    else:
        qty, fromC, toC = query.split(" ")
        fromC = fromC.upper()
        toC = toC.upper()
        qty = float(round(int(qty), 2))
        amount = round(qty * fx[toC] / fx[fromC], 2)
        print(f"{qty} of currency {fromC} amounts to {amount} of currency {toC} today")

try:
    function1()
except KeyError:
    print("You seem to have inputted wrongly, retry!")
    function1()

21.制作一个简单的秒表

import tkinter as Tkinter
from datetime import datetime
counter = 0
running = False

def counter_label(label):
    def count():
        if running:
            global counter
            # 管理初始延迟
            if counter == 0:
                display = 'Ready!'
            else:
                tt = datetime.utcfromtimestamp(counter)
                string = tt.strftime('%H:%M:%S')
                display = string

            label['text'] = display

            # 标签之后(arg1,arg2)延迟以毫秒为单位的第一个参数,然后调用作为第二个参数的函数。通常像这里一样,我们需要重复调用它所在的函数。延迟1000ms=1秒,并再次调用计数。
            label.after(1000, count)
            counter += 1

    # 触发计数器的启动
    count()

# 秒表的启动功能
def Start(label):
    global running
    running = True
    counter_label(label)
    start['state'] = 'disabled'
    stop['state'] = 'normal'
    reset['state'] = 'normal'

# 秒表的停止功能
def Stop():
    global running
    start['state'] = 'normal'
    stop['state'] = 'disabled'
    reset['state'] = 'normal'
    running = False

# 秒表的重置功能
def Reset(label):
    global counter
    counter = 0
    # 如果按下停止按钮后按下复位按钮。
    if not running:
        reset['state'] = 'disabled'
        label['text'] = '00:00:00'
    # If reset is pressed while the stopwatch is running.
    else:
        label['text'] = '00:00:00'

root = Tkinter.Tk()
root.title("Stopwatch")

# 修复窗口大小
root.minsize(width=250, height=70)
label = Tkinter.Label(root, text='Ready!', fg='black', font='Verdana 30 bold')
label.pack()
f = Tkinter.Frame(root)
start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label))
stop = Tkinter.Button(f, text='Stop', width=6, state='disabled', command=Stop)
reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', command=lambda: Reset(label))
f.pack(anchor='center', pady=5)
start.pack(side='left')
stop.pack(side='left')
reset.pack(side='left')
root.mainloop()

22.用于压缩文件夹和文件的Python脚本

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:
            # 使用os模块创建完整的文件路径。
            file_path = os.path.join(root, filename)
            file_paths.append(file_path)

    # 返回所有路径
    return file_paths

def zip_dir(dir_path, file_paths):
    # 将文件和文件夹写入zip文件
    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')

23.文字转语音

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

以上就是23个很棒的Python脚本集合分享(迷你项目)的详细内容,更多关于Python脚本的资料请关注我们其它相关文章!

(0)

相关推荐

  • 13个简便高效的Python脚本分享

    目录 1.使用 Python 进行速度测试 2.在谷歌上搜索 3.制作网络机器人 4.获取歌曲歌词 5.获取照片的Exif数据 6.提取图像中的 OCR 文本 7.将照片转换为Cartonize 8.清空回收站 9.Python 图像增强 10.获取 Window 版本 11.将 PDF 转换为图像 12.转换十六进制到 RGB 13.网站状态 每天我们都会面临许多需要高级编码的编程挑战.你不能用简单的 Python 基本语法来解决这些问题.在本文中,我将分享 13 个高级 Python 脚本,

  • Python 自动备份脚本的示例代码

    目录 一.前言 二.代码 一.前言 之前因为疫情常常不知道会不会被封在家里,又不想把电脑带过来带过去,就做了这个自动备份的脚本. 功能如下: 自动从指定根目录里将找到的所有指定后缀名的文件备份到一个备份文件夹里: 将备份文件夹中的文件自动和阿里云盘同步: 原文件目录结构不会改变: 可以屏蔽根目录下一级中不想要的文件夹/文件,下多级的不行: 定时运行: 二.代码 创建了一个AutoTransfer类,这个类在初始化的时候会自动读取配置文件里的参数,如果没有配置文件也可以后续调用函数时来传参. 调用

  • python中的脚本性能分析

    目录 python脚本性能分析 python性能分析技巧 1.分析一行代码 2.分析多行代码 3.代码块中的每一行代码进行时间分析 python脚本性能分析 首先使用cd进入需要测试的脚本文件对应的目录,然后再使用如下代码完成对脚本的性能测试. # enter the directory of document cd (file directory) # use pdb library for debuging python -m cProfile test.py 我们可以看到我们获取到了每一步

  • 利用Python脚本实现传递参数的三种方式分享

    目录 一.使用sys.argv的数组传入 二.使用argparse包传入 三.使用shell脚本的方式向python脚本传递参数 背景:使用python脚本传递参数在实际工作过程中还是比较常用,以下提供了好几种的实现方式: 一.使用sys.argv的数组传入 说明:使用sys.argv必须按照先后的顺序传入对应的参数:sys.argv则封装了传入的参数数据,作为数组的方式已经传入 import sys print("传入参数的总长度为:", len(sys.argv)) print(&

  • 四个Python操作Excel的常用脚本分享

    目录 一.安装openpyxl模块 二.加载库 三.创建文件和工作表 四.在工作表指定单元格写数据 五.设置单元格的颜色字体 六.在excel中写入表格 一.安装openpyxl模块 Python操作excel主要用到了openpyxl模块,按win+R打开cmd,在里面输入 pip3 install openpyxl 即可成功安装openpyxl模块. 二.加载库 接着加载库,并设置数据存放的文件夹. import os import random import openpyxl import

  • 分享十个Python提高工作效率的自动化脚本

    目录 01.解析和提取 HTML 02.二维码扫描仪 03.截图 04.创建有声读物 05.PDF 编辑器 06.迷你 Stackoverflow 07.自动化手机 08.监控 CPU/GPU 温度 09.Instagram 上传机器人 10.视频水印 在这个自动化时代,我们有很多重复无聊的工作要做. 想想这些你不再需要一次又一次地做的无聊的事情,让它自动化,让你的生活更轻松. 那么在本文中,我将向您介绍 10 个 Python 自动化脚本,以使你的工作更加自动化,生活更加轻松. 因此,没有更多

  • Python桌面文件清理脚本分享

    目录 需求 所以脚本需要具有以下功能 实现 目录结构 代码 需求 桌面临时文件较多时,直接删了不太放心,不删又显得很杂乱,故需要写一个脚本批量清理并备份这些鸡肋的文件. 所以脚本需要具有以下功能 1. 可以将桌面文件移动至指定文件夹(可配置). 2. 可以设置例外文件,比如桌面图标不需要移动,部分常用的文件也不需要移动. 3. 出现同名文件时,不能直接覆盖,需要加一个日期后缀予以区分.例如更名为 helloworld-2022-08-30.txt 本来准备按照文件后缀名分文件夹存放的,但毕竟是临

  • 7个很棒的Vue开发技巧分享

    目录 1.路由参数解耦 2.功能组件 3.样式范围 4.watch的高级使用 5.watch监听多个变量 6.事件参数$event 7.程序化事件监听器 1.路由参数解耦 通常在组件中使用路由参数,大多数人会做以下事情. export default { methods: { getParamsId() { return this.$route.params.id } } } 在组件中使用 $route 会导致与其相应路由的高度耦合,通过将其限制为某些 URL 来限制组件的灵活性.正确的做法是通

  • 八个一看就觉得很棒的Vue开发技巧分享

    目录 1.路由参数解耦 2.功能组件 3.样式范围 4.watch的高级使用 5.watch监听多个变量 6.事件参数$event 7.程序化事件监听器 8.监听组件生命周期 总结 1.路由参数解耦 通常在组件中使用路由参数,大多数人会做以下事情. export default { methods: { getParamsId() { return this.$route.params.id } } } 在组件中使用 $route 会导致与其相应路由的高度耦合,通过将其限制为某些 URL 来限制

  • 在python 脚本下解析json数据

    在项目中遇到了个json数据需要解析,利用Python脚本尝试分享给大家 如下: import os import pandas as pd import numpy as np path=r'C:\users\....' #文件的上一层路径 key=['SS','AA',....] #字段名 files = os.listdir(path) all_data = [] for file in files:         filepath = os.path.join(path,file) d

  • Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例

    每种语言都有自己的优势,互相结合起来各取所长程序执行起来效率更高或者说哪种实现方式较简单就用哪个,nodejs是利用子进程来调用系统命令或者文件,文档见http://nodejs.org/api/child_process.html,NodeJS子进程提供了与系统交互的重要接口,其主要API有: 标准输入.标准输出及标准错误输出的接口. NodeJS 子进程提供了与系统交互的重要接口,其主要 API 有: 标准输入.标准输出及标准错误输出的接口 child.stdin 获取标准输入 child.

  • 使用Python脚本在Linux下实现部分Bash Shell的教程

    对于Linux用户来说,命令行的名声相当的高.不像其他操作系统,命令行是一个可怕的命题,但是对于Linux社区中那些经验丰富的大牛,命令行却是最值得推荐鼓励使用的.通常,命令行对比图形用户界面,更能提供更优雅和更高效的解决方案. 命令行伴随着Linux社区的成长,UNIX shells,例如 bash和zsh,已经成长为一个强大的工具,也是UNIX shell的重要组成部分.使用bash和其他类似的shells,可以得到一些很有用的功能,例如,管道,文件名通配符和从文件中读取命令,也就是脚本.

  • 使用Python脚本对Linux服务器进行监控的教程

    目前 Linux 下有一些使用 Python 语言编写的 Linux 系统监控工具 比如 inotify-sync(文件系统安全监控软件).glances(资源监控工具)在实际工作中,Linux 系统管理员可以根据自己使用的服务器的具体情况编写一下简单实用的脚本实现对 Linux 服务器的监控. 本文介绍一下使用 Python 脚本实现对 Linux 服务器 CPU 内存 网络的监控脚本的编写. Python 版本说明 Python 是由 Guido van Rossum 开发的.可免费获得的.

  • Python脚本简单实现打开默认浏览器登录人人和打开QQ的方法

    本文实例讲述了Python脚本简单实现打开默认浏览器登录人人和打开QQ的方法.分享给大家供大家参考,具体如下: 每天打开电脑第一件事应该就是打开人人刷一下,然后登上QQ.每次都这样很麻烦,于是写了一个脚本,每次双击即可自动完成这两个工作. 注意:需要在人人登录时选择"下次自动登录",QQ也要选择自动登录.其实感觉这些设置都是没必要的,都可以用脚本完成,但是本人比较水,就偷了懒,没有去查资料. 代码如下: todo.pyw: import webbrowser import os web

  • 分析用Python脚本关闭文件操作的机制

    如果不用"with",那么Python会在何时关闭文件呢?答案是:视情况而定. Python程序员最初学到的东西里有一点就是可以通过迭代法很容易地遍历一个打开文件的全文: f = open('/etc/passwd') for line in f: print(line) 注意上面的代码具有可行性,因为我们的文件对象"f"是一个迭代器.换句话说,"f" 知道在一个循环或者任何其他的迭代上下文中做什么,比如像列表解析. 我的Python课堂上的大多

  • 使用Python脚本来控制Windows Azure的简单教程

    inux开发人员经常使用 Python 完成小块的工作,因为你可以编写脚本的情况很容易.它已经成为完成配置和部署等小任务的一个流行方式.Windows Azure,微软的云,也没有什么不同.通过 Python SDK 所提供的可用性,Python 成为 Windows Azure 的头等公民.让我们看看我们如何能够使用Python无需其它而只需一个Windows Azure订阅就可以用编程方式从 vmdepot 部署一个映像到 Windows Azure上. 建立一个管理证书 任何与 Windo

  • 使用IronPython把Python脚本集成到.NET程序中的教程

    从两个优秀的世界各取所需,更高效的复用代码.想想就醉了,.NET和python融合了."懒惰"的程序员们,还等什么? Jesse Smith为您展示如何两个语言来服务同一个.NET程序.你能集两家所长:Python和.NET一起工作,提供可重用的代码功能而不需要你为了一个环境重写代码库. 通过使用IronPython 运行时库,你可以让Python脚本运行在你的.NET程序中.本文向你展示如何使用一个.NET程序中的python脚本获取并展示用户反馈. 如果你曾经有在一个.NET程序中

随机推荐