50个开发必备的Python经典脚本(41-50)

目录

41. 彩色图像到黑白图像转换器

所需的库

用法

例子

42. CricBuzz 分数更新

如何跑

43.CSV 到 Excel

要求

44. 当前城市天气

45. 目录管理器

46. Excel 文件合并

所需的库

用法

47. 扩展IP地址信息

运行程序

输出

48.列表转换器的Excel到Python列表

所需的库

用法

49. Python 中的文件资源管理器对话框

1.使用tkinter

2.使用PyQt

50. 文件共享机器人


建议收藏备用

41. 彩色图像到黑白图像转换器

一个简单的 Python 脚本,它将彩色图像文件名作为参数,将其转换为灰度图像并保存输出图像文件。它展示了 Pillow 库的基本用法。

所需的库

  1. 枕头 (PIL) $pip install Pillow

用法

  1. 转到脚本的文件夹并打开命令提示符。
  2. 运行命令: $python bw_convert.py <image_file_name>

例子

$python bw_convert.py sample_image.jpg $python bw_convert.py sample_image.png

import sys
from PIL import Image
from PIL.ExifTags import TAGS

image_file = sys.argv[1]
image_name = image_file.split(".")[0]

try:
    image = Image.open(image_file)
except IOError:
    print("Error in loading image!!")
    sys.exit(1)

bw_image = image.convert('L')
bw_image.save("bw_"+image_name+".png")

42. CricBuzz 分数更新

这个基于网络抓取的 Python 脚本使用 Beautiful soup 库抓取数据来获取最近的板球比赛得分。

如何跑

在终端中输入此命令。

python3 cricbuzz_scrap.py

它将显示最近所有比赛的比分更新。

from urllib.request import urlopen
from bs4 import BeautifulSoup

quote_page = 'http://www.cricbuzz.com/cricket-match/live-scores'
page = urlopen(quote_page)
soup = BeautifulSoup(page,'html.parser')

update=[]

for score in soup.find_all('div',attrs={'class':'cb-col cb-col-100 cb-lv-main'}):
    s=score.text.strip()
    update.append(s)

print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*')


for i in range(len(update)):
    print(i+1),
    print(update[i])
print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*')

43.CSV 到 Excel

该程序将任何逗号分隔值文件(例如:.csv 或 .data)中的数据写入 Excel 文件。

要求

安装所需的库:

$ pip install openpyxl

之后运行:

$ python main.py 

输入文件示例

#!python3
# -*- coding: utf-8 -*-

import openpyxl
import sys

#inputs
print("This programme writes the data in any Comma-separated value file (such as: .csv or .data) to a Excel file.")
print("The input and output files must be in the same directory of the python file for the programme to work.\n")

csv_name = input("Name of the CSV file for input (with the extension): ")
sep = input("Seperator of the CSV file: ")
excel_name = input("Name of the excel file for output (with the extension): ")
sheet_name = input("Name of the excel sheet for output: ")

#opening the files
try:
    wb = openpyxl.load_workbook(excel_name)
    sheet = wb.get_sheet_by_name(sheet_name)

    file = open(csv_name,"r",encoding = "utf-8")
except:
    print("File Error!")
    sys.exit()

#rows and columns
row = 1
column = 1

#for each line in the file
for line in file:
    #remove the \n from the line and make it a list with the seperator
    line = line[:-1]
    line = line.split(sep)

    #for each data in the line
    for data in line:
        #write the data to the cell
        sheet.cell(row,column).value = data
        #after each data column number increases by 1
        column += 1

    #to write the next line column number is set to 1 and row number is increased by 1
    column = 1
    row += 1

#saving the excel file and closing the csv file
wb.save(excel_name)
file.close()

44. 当前城市天气

使用 GET 请求检索您所在城市当前天气的详细信息,只需插入任何城市的名称,它将提供当前温度、当前风速和当前天气类型等详细信息。

import requests


def get_temperature(json_data):
    temp_in_celcius = json_data['main']['temp']
    return temp_in_celcius

def get_weather_type(json_data):
    weather_type = json_data['weather'][0]['description']
    return weather_type

def get_wind_speed(json_data):
    wind_speed = json_data['wind']['speed']
    return wind_speed



def get_weather_data(json_data, city):
    description_of_weather = json_data['weather'][0]['description']
    weather_type = get_weather_type(json_data)
    temperature = get_temperature(json_data)
    wind_speed = get_wind_speed(json_data)
    weather_details = ''
    return weather_details + ("The weather in {} is currently {} with a temperature of {} degrees and wind speeds reaching {} km/ph".format(city, weather_type, temperature, wind_speed))


def main():
    api_address = 'https://api.openweathermap.org/data/2.5/weather?q=Sydney,au&appid=a10fd8a212e47edf8d946f26fb4cdef8&q='
    city = input("City Name : ")
    units_format = "&units=metric"
    final_url = api_address + city + units_format
    json_data = requests.get(final_url).json()
    weather_details = get_weather_data(json_data, city)
    # print formatted data
    print(weather_details)

main()

45. 目录管理器

根据类型(常见扩展名)组织给定目录中的文件。无法识别的扩展名保留在父目录本身中,而其他扩展名则移动到相应的新目录,例如“图片”等。

python main.py [-h] 目录路径

#!/usr/bin/python3

import argparse
import os


def path():
    parse = argparse.ArgumentParser(
        add_help=True, description="Organize your files to different directories according to their type")
    parse.add_argument('directory_path', type=str, default='./',
                       help="The absolute path to the directory")
    return parse.parse_args().directory_path


documents = ['.log', '.txt', '.doc', '.docx', '.md', '.pdf', '.wps']
picture = ['.png', '.jpg', 'jpeg', '.bmp']
music = ['.mp3', '.wav']
compressed = ['.zip', '.rar', '.tar', '.gz', '.bz2', '.xz']
video = ['.3gp', '.mov', '.mp4', '.mkv', '.srt', '.avi']
web = ['.html', .'.css', '.js']
source = ['.py', '.c', '.cpp', '.java',]


directories = [path() + '/Compressed', path() + '/Documents',
               path() + '/Pictures', path() + '/Music', path() + '/Video', path() + '/Web', path() + '/Source-codes',]

print("This will organize your files to different directories according to their type!!")
print("Are you sure you want to continue? (y/n)")
flag = input('>>>')
if flag.lower() == 'y':
    try:
        for d in directories:
            os.mkdir(d)
    except FileExistsError:
        pass

    for files in os.listdir(path()):
        dot = (files.rfind('.'))
        if dot is not 0 and dot is not -1:
            if files[dot:].lower() in music:
                os.rename(path() + '/' + files, path() + '/Music/' + files)
            if files[dot:].lower() in picture:
                os.rename(path() + '/' + files, path() + '/Pictures/' + files)
            if files[dot:].lower() in documents:
                os.rename(path() + '/' + files, path() + '/Documents/' + files)
            if files[dot:].lower() in compressed:
                os.rename(path() + '/' + files, path() +
                          '/Compressed/' + files)
            if files[dot:].lower() in video:
                os.rename(path() + '/' + files, path() + '/Video/' + files)
            if files[dot:].lower() in web:
                os.rename(path() + '/' + files, path() + '/Web/' + files)
            if files[dot:].lower() in source:
                os.rename(path() + '/' + files, path() + '/Source-codes/' + files)    

    for d in directories:
        if os.listdir(d) is None:
            os.removedirs(d)
else:
    print("Exiting")
    os.sys.exit(0)

46. Excel 文件合并

一个简单的脚本,将给定路径中具有类似表结构的 Excel 文件作为输入,并创建统一的 Excel 工作簿。

所需的库

  1. 开放式pyxl $pip install openpyxl

用法

提供了示例脚本“将 excel 文件合并到 1.py”来展示 Excel 合并的用法。运行脚本时,它将询问统一工作簿的名称以及包含需要合并的 Excel 文件的文件夹的路径。

from openpyxl import load_workbook
from openpyxl import Workbook
import os


# Read data from active worksheet and return it as a list
def reader(file):
    global path
    abs_file = os.path.join(path, file)
    wb_sheet = load_workbook(abs_file).active
    rows = []
    # min_row is set to 2, ignore the first row which contains headers
    for row in wb_sheet.iter_rows(min_row=2):
        row_data = []
        for cell in row:
            row_data.append(cell.value)
        rows.append(row_data)
    return rows


# You can replace these with your own headers for the table
headers = ['Nume', 'Prenume', 'Titlu', 'Editura', 'Cota', 'Pret', 'An']
# Unified excel name
workbook_name = input('Unified Workbook name ')
book = Workbook()
sheet = book.active
# Specify path
path = input('Path: ')
# Get all files from folder
files = os.listdir(path)
for file in files:
    rows = reader(file)
    for row in rows:
        sheet.append(row)
    book.save(filename=workbook_name)

47. 扩展IP地址信息

从终端查看有关您的公共 IP 地址的扩展信息。

python 脚本 curl 使用以下参数运行

curl -H "Accept: application/json" [https://ipinfo.io/json](https://ipinfo.io/json)

运行程序

python extended_ip_address_info.py

输出

输出应采用以下形式:

{  
  "ip": "xxx.xxx.xxx.xxx",  
  "city": "A_city",  
  "hostname": "host.isp-website.com",  
  "region": "A_region",  
  "country": "Country code",  
  "loc": "coordinates",  
  "org": "AS-number ISP-name",  
  "postal": "postal-code",  
  "timezone": "Europe/City",  
  "readme": "https://ipinfo.io/missingauth"  
}
#!/bin/python   
# -*- coding: utf-8 -*-

# Using curl to get data from https://ipinfo.io/json
# Template from pycurl documentation
# http://pycurl.io/docs/latest/quickstart.html#examining-response-headers

import pycurl #curl library
import certifi #HTTP over TLS/SSL library
from io import BytesIO #Buffered I/O implementation using an in-memory bytes buffer.

#set header, '--header' or -H
header = ['Accept: application/json']

buffer = BytesIO()
c = pycurl.Curl() #curl
c.setopt(c.HTTPHEADER, header) #header
c.setopt(c.URL, 'https://ipinfo.io/json') #URL
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.CAINFO, certifi.where()) # SSL certificates
c.perform()
c.close()

body = buffer.getvalue()
# Body is a byte string.
# We have to know the encoding in order to print it to a text file
# such as standard output.
print(body.decode('iso-8859-1'))

48.列表转换器的Excel到Python列表

一个简单的工具,可以读取 Excel 文件和任何相应的工作表,并将其转换为列表数据结构的 Python 列表。

所需的库

  1. xlrd $pip install xlrd

用法

已提供示例脚本 excel_to_list_usage.py 来展示 ExcelToList 的用法。它读取 Excel 及其工作表,并打印列表列表。

import xlrd
import sys

class ExcelToList():

    def __init__(self, file, sheet):
        self.file = file
        self.sheet = sheet

    def convert(self):
        converted_list = []
        inputexcel = xlrd.open_workbook(self.file)
        inputsheet = inputexcel.sheet_by_name(self.sheet)
        numberofrows = inputsheet.nrows
        numberofcols = inputsheet.ncols
        start_row,start_col = 0,0
        for current_row in range(start_row,numberofrows):
            currentlist = []
            for current_col in range(start_col,numberofcols):
                currentlist.append(inputsheet.cell(current_row,current_col).value)
            converted_list.append(currentlist)
        return converted_list

点击这里了解更多详情

49. Python 中的文件资源管理器对话框

打开文件资源管理器对话框 UI 以使用 Python 选择文件。

1.使用tkinter

使用 tkinter 的示例:

$ python select_file_tk.py
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()
print(file_path)

2.使用PyQt

安装 PyQt5

使用 PyQt5 的示例:

$ python select_file_pyqt.py
from PyQt5.QtWidgets import QFileDialog, QApplication
from PyQt5 import QtWidgets


def select_files(directory_location=None):
    qtapp = QApplication([directory_location])
    qtwgt = QtWidgets.QWidget()
    filenames, _ = QFileDialog.getOpenFileNames(qtwgt)
    return filenames


def main():
    filenames = select_files()
    print("You selected:\n", "\n".join(filename for filename in filenames))


if __name__ == "__main__":
    main()

50. 文件共享机器人

用Python开发的文件共享电报机器人它就像一个集中的文件存储库,授权用户可以在其中共享文件,并且文件对所有用户都可用。使用/help命令可以查看功能和命令。该机器人可以直接托管在 Heroku 上。

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import os
import telegram
import shutil
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

#list of authorized users
#create a list of telegram usernames to authorise them, 0th username is admin.
username_list = []
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
    """Send a message when the command /start is issued."""
    reply = "Welcome to World of Automation. \nI am a bot developed by a Lazy Programmer.\nSend /help command to see what i can do."
    update.message.reply_text(reply)


def help(bot, update):
    """Send a message when the command /help is issued."""
    admin = update.message.from_user.username
    if admin == username_list[0]:
        reply = '''Send /get folder_name/file_name.extension to receive a file. 
                \nSend /ls folder_name to show list of files.
                \nSend /put folder_name/file_name.extension to upload last sent file.
                \nSend /mkdir folder_name to create a Folder.
                \nSend /remove folder_name/filename.extension to delete a file.
                \nSend /adduser username to give access.
                \nSend /removeuser username to revoke access.
                \nSend /showuser to show list of users
                '''    
    else:
        reply = '''Send /get folder_name/file_name.extension to receive a file. 
                \nSend /ls folder_name to show list of files.
                \nSend /put folder_name/file_name.extension to upload last sent file.
                \nSend /mkdir folder_name to create a Folder.
                '''
    update.message.reply_text(reply)


def get(bot, update):
    """Send requested file."""
    username = update.message.from_user.username
    if(username not in username_list):
        update.message.reply_text("You are not Authorized.")
        return
    file = update.message.text.split(" ")[-1]
    if(file == "/send"):
        update.message.reply_text("Invalid File name.")
    else:
        reply = "Findind and Sending a requested file to you. Hold on..."
        update.message.reply_text(reply)
        path = os.getcwd()+'/'+file
        if (os.path.exists(path)):
            bot.send_document(chat_id=update.message.chat_id,document=open(path, 'rb'), timeout = 100)
        else:
            update.message.reply_text("File not Found.")

def ls(bot, update):
    """Show files in requested directory."""
    username = update.message.from_user.username
    if(username not in username_list):
        update.message.reply_text("You are not Authorized.")
        return
    file = update.message.text.split(" ")[-1]
    if(file == "/show"):
        update.message.reply_text("Invalid Directory name.")
    else:
        reply = "Findind and Sending a list of files to you. Hold on..."
        update.message.reply_text(reply)
        path = os.getcwd()+'/'+file
        if (os.path.exists(path)):
            update.message.reply_text(os.listdir(path))
        else:
            update.message.reply_text("Directory not Found.")

def put(bot, update):
    f = open(str(os.getcwd())+"/file", "r")
    file_id = f.read()
    f.close
    if file_id == "":
        update.message.reply_text("You didn't upload file.")
    else:
        new_file = bot.get_file(file_id)
        message = update.message.text.split(" ")
        path = message[-1]
        if len(path) < 1:
            update.message.reply_text("Enter Path correctly.")
        else:
            new_file.download(os.getcwd()+'/'+path)
            update.message.reply_text("File Stored.")


def mkdir(bot, update):
    message = update.message.text.split(" ")
    if len(message) < 1 or message[-1] == "/mkdir":
        update.message.reply_text("Invalid Syntax. Refer syntax in help section.")
        return
    path = os.getcwd() + "/" + message[-1]
    os.mkdir(path)
    update.message.reply_text("Folder Created.")


def echo(bot, update):
    """Echo the user message."""
    if update.message.document:
        file_id = update.message.document.file_id
        f = open(str(os.getcwd())+"/file", "w")
        f.write(file_id)
        f.close
        update.message.reply_text("Received.Now send file name and location to store. using /put command")
    else:
        reply = "Invalid Input."
        update.message.reply_text(reply)

def error(bot, update, error):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, error)

def add_user(bot, update):
    admin = update.message.from_user.username
    if admin == username_list[0]:
        username = update.message.text.split(" ")[-1]
        username_list.append(username)
        update.message.reply_text("User added.")
    else:
        update.message.reply_text("You are not Authorized.")

def show_user(bot, update):
    admin = update.message.from_user.username
    if admin == username_list[0]:
        update.message.reply_text(username_list)
    else:
        update.message.reply_text("You are not Authorized.")

def remove_user(bot, update):
    admin = update.message.from_user.username
    if admin == username_list[0]:
        username = update.message.text.split(" ")[-1]
        username_list.remove(username)
        update.message.reply_text("User Removed.")
    else:
        update.message.reply_text("You are not Authorized.")

def remove(bot, update):
    admin = update.message.from_user.username
    if admin == username_list[0]:
        filename = update.message.text.split(" ")[-1]
        os.remove(os.getcwd()+ "/" + filename)
        update.message.reply_text("File Removed.")
    else:
        update.message.reply_text("You are not Authorized.")

def rmdir(bot, update):
    admin = update.message.from_user.username
    if admin == username_list[0]:
        filename = update.message.text.split(" ")[-1]
        shutil.rmtree(os.getcwd()+ "/" + filename)
        update.message.reply_text("Folder Removed.")
    else:
        update.message.reply_text("You are not Authorized.")

def main():
    """Start the bot."""
    # Create the EventHandler and pass it your bot's token.
    TOKEN = os.environ['TOKEN']
    updater = Updater(TOKEN)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("get", get))
    dp.add_handler(CommandHandler("ls", ls))
    dp.add_handler(CommandHandler("put", put))
    dp.add_handler(CommandHandler("mkdir", mkdir))

    #admin functionalities
    dp.add_handler(CommandHandler("adduser", add_user))
    dp.add_handler(CommandHandler("showuser", show_user))
    dp.add_handler(CommandHandler("removeUser", remove_user))
    dp.add_handler(CommandHandler("remove", remove))
    dp.add_handler(CommandHandler("rmdir", rmdir))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.document, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()


if __name__ == '__main__':
    main()
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极致人生-010

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值