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

目录

31. 数独求解器

如何使用它?

运行脚本。

32. 文件加密解密

用法

34. 自动电子邮件

要求:Python 版本 3、Smtplib 和 JSON

35. 人工智能聊天机器人

什么是人工智能机器人?

如何使用它?

36. 比特币价格 GUI 应用程序

如何使用

37. Codechef 自动提交

38. 校验和

例子:

39. 加密货币转换器

要求

用法

40. 加密货币价格

要求


建议收藏备用

50个开发必备的Python经典脚本(31-40)_第1张图片

31. 数独求解器

这是一个使用 Python 求解 9x9 数独矩阵的脚本。

如何使用它?

  1. 编辑 app.py 以添加您的数独矩阵。(填充 0 空单元格。)

例如,

[[8, 1, 0, 0, 3, 0, 0, 2, 7],  
[0, 6, 2, 0, 5, 0, 0, 9, 0],  
[0, 7, 0, 0, 0, 0, 0, 0, 0],  
[0, 9, 0, 6, 0, 0, 1, 0, 0],  
[1, 0, 0, 0, 2, 0, 0, 0, 4],  
[0, 0, 8, 0, 0, 5, 0, 7, 0],  
[0, 0, 0, 0, 0, 0, 0, 8, 0],  
[0, 2, 0, 0, 1, 0, 7, 5, 0],  
[3, 8, 0, 0, 7, 0, 0, 4, 2]]

运行脚本。

python3 app.py

这将为您提供控制台上的输出。输出将包含输入数独矩阵和已求解的数独矩阵。

输入=>

8 1 0 | 0 3 0 | 0 2 7  
0 6 2 | 0 5 0 | 0 9 0  
0 7 0 | 0 0 0 | 0 0 0  
---------------------  
0 9 0 | 6 0 0 | 1 0 0  
1 0 0 | 0 2 0 | 0 0 4  
0 0 8 | 0 0 5 | 0 7 0  
---------------------  
0 0 0 | 0 0 0 | 0 8 0  
0 2 0 | 0 1 0 | 7 5 0  
3 8 0 | 0 7 0 | 0 4 2  

输出=>

8 1 9 | 4 3 6 | 5 2 7  
4 6 2 | 7 5 1 | 3 9 8  
5 7 3 | 2 9 8 | 4 1 6  
---------------------  
2 9 4 | 6 8 7 | 1 3 5  
1 5 7 | 9 2 3 | 8 6 4  
6 3 8 | 1 4 5 | 2 7 9  
---------------------  
7 4 5 | 3 6 2 | 9 8 1  
9 2 6 | 8 1 4 | 7 5 3  
3 8 1 | 5 7 9 | 6 4 2
def printsudoku(sudoku):
    print("\n\n")
    for i in range(len(sudoku)):
        line = ""
        if i == 3 or i == 6:
            print("---------------------")
        for j in range(len(sudoku[i])):
            if j == 3 or j == 6:
                line += "| "
            line += str(sudoku[i][j])+" "
        print(line)
    print("\n\n")

def findNextCellToFill(sudoku):
    for x in range(9):
        for y in range(9):
            if sudoku[x][y] == 0:
                return x, y
    return -1, -1

def isValid(sudoku, i, j, e):
    rowOk = all([e != sudoku[i][x] for x in range(9)])
    if rowOk:
        columnOk = all([e != sudoku[x][j] for x in range(9)])
        if columnOk:
            secTopX, secTopY = 3*(i//3), 3*(j//3)
            for x in range(secTopX, secTopX+3):
                for y in range(secTopY, secTopY+3):
                    if sudoku[x][y] == e:
                        return False
            return True
    return False

def solveSudoku(sudoku, i=0, j=0):
    i, j = findNextCellToFill(sudoku)
    if i == -1:
        return True
    for e in range(1, 10):
        if isValid(sudoku, i, j, e):
            sudoku[i][j] = e
            if solveSudoku(sudoku, i, j):
                return True
            sudoku[i][j] = 0
    return False
32. 文件加密解密

一个命令行 Python 脚本,可以加密给定文件并解密加密文件。

用法

  • 加密文件
$ pipenv run python crypt -e file.txt
  • 解密文件
$ pipenv run python crypt -d file.enc
import os
import argparse

from cryptography.fernet import Fernet

class Crypt:

    def __init__(self):

        # can be generated Fernet.generate_key()
        # if generated, save it below
        self.key = b'oBa5LeeJt1r4BmNyJXb6FHd1U21GMshH9Pqu_J-HzNQ='
        self.fernet = Fernet(self.key)

    def encrypt(self, input_file_path):
        """
        Encrypt a file
        """

        # split the file and take only the file name
        base_name = os.path.basename(input_file_path).split('.')[0].split('-')[-1]

        # creates a file name with extension .enc
        output_file = f"{base_name}.enc"
        if os.path.exists(output_file):
            print(f'Encrypted File already exists')
        else:
            with open(input_file_path, 'rb') as i:
                input_data = i.read()

            encrypted = self.fernet.encrypt(input_data)

            with open(output_file, 'wb') as o:
                o.write(encrypted)
            print(f'Encrypted file: {output_file}\n')


    def decrypt(self, input_file_path, output_file_ext='txt'):
        """
        Decrypt an already encrypted file
        """

        # split the file and take only the file name
        base_name = os.path.basename(input_file_path).split('.')[0].split('-')[-1]
        output_file = f'{base_name}.{output_file_ext}'
        with open(input_file_path, 'rb') as f:
            file_data = f.read()

        decrypted = str(self.fernet.decrypt(file_data), 'utf-8')

        with open(output_file, 'w') as o:
            o.write(decrypted)
        print(f'Decrypted file: {output_file}\n')


if __name__ == '__main__':
    crypt = Crypt()

    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-e', '--encrypt',
                        help='Encrpyt the file')
    parser.add_argument('-d', '--decrypt', 
                        help='Decrypt the file')

    args = parser.parse_args()

    if args.encrypt:
        print(f'Input file: {args.encrypt}')
        crypt.encrypt(args.encrypt)
    elif args.decrypt:
        print(f'Input file: {args.decrypt}')
        crypt.decrypt(args.decrypt)
33. 地址地点

该脚本会将您的地址转换为坐标。

import geocoder
t=input("enter the location:")
g = geocoder.arcgis(t)
print(g.latlng)

34. 自动电子邮件

自动电子邮件 python 脚本 现在,您只需使用 Python 中的 Smtplib 模块,只需点击几下即可轻松地向多人发送电子邮件

要求:Python 版本 3、Smtplib 和 JSON

pip install smtplib  
pip install json

可以使用命令提示符(Python自动化_email.py)轻松运行->像登录Gmail帐户一样登录(相同的电子邮件和密码)->使用直观的用户友好菜单找到您的方式(您的密码和电子邮件仅存储在您的本地设备,否则任何人都无法访问您的信息!)

from smtplib import SMTP as smtp
import json

def sendmail(sender_add, reciever_add, msg, password):
    server = smtp('smtp.gmail.com:587')
    server.starttls()
    server.login(sender_add, password)
    server.sendmail(sender_add, reciever_add, msg)
    print("Mail sent succesfully....!")


group = {}
print('\t\t ......LOGIN.....')
your_add = input('Enter your email address :')
password = input('Enter your email password for login:')
print('\n\n\n\n')
choice = 'y'
while(choice != '3' or choice != 'no'):
    print("\n 1.Create a group\n2.Message a group\n3.Exit")
    choice = input()
    if choice == '1':
        ch = 'y'
        while(ch != 'n'):
            gname = input('Enter name of group :')
            group[gname] = input('Enter contact emails separated by a single space :').rstrip()
            ch = input('Add another....y/n? :').rstrip()
        with open('groups.json', 'a') as f:
            json.dump(group, f)
    elif choice == '2':
        gname = input('Enter name of group :')
        try:
            f = open('groups.json', 'r')
            members = json.load(f)
            f.close()
        except:
            print('Invalid group name. Please Create group first')
            exit
        members = members[gname].split()
        msg = input('Enter message :')
        for i in members:
            try:
                sendmail(your_add, i, msg, password)
            except:
                print("An unexpected error occured. Please try again later...")
                continue
    else:
        break

35. 人工智能聊天机器人

什么是人工智能机器人?

聊天机器人(也称为谈话机器人、聊天机器人、机器人、IM 机器人、交互式代理或人工对话实体)是一种通过听觉或文本方法进行对话的计算机程序或人工智能。

如何使用它?

首先在 UNIX 终端或 Windows CMD 上运行以下命令:

$ python bash.py
import sys
try:
    import aiml
except ImportError:
    print('[!] Failed to import the module')
    try:
        select = raw_input('[*] Attempt to auto-install aiml? [Y/n')
    except KeyboardInterrupt:
        print('\n[!] User Cancel')
        sys.exit(5)
    if select.strip().lower()[0] == 'y':
        print('[*] Trying to Install aiml... ')
        sys.stdout.flush()
        try:
            import pip
            pip.main(['install', '-q', 'aiml'])
            import aiml
            print('Finished')
        except Exception:
            print('Something happens PLease check your internet connection')
            sys.exit(5)

    elif select.strip().lower()[0] == 'n':
        print('[*] User cancel Auto-install')
        sys.exit(5)


kern = aiml.Kernel()
kern.learn('load.xml')
kern.respond('load aiml b')

while True:
    print(kern.respond(raw_input('Type your Message >>')))

36. 比特币价格 GUI 应用程序

使用 Python 的 Tkinter 库和免费的 Luno API 告知比特币的当前价格。按刷新即可获取最新价格。

如何使用

> _python bitcoin-price.py_

或者

> _python3 bitcoin-price.py_

默认货币对是比特币兑马来西亚林吉特,要更改该货币对,请单击 此处 了解可用的代码并 XBTMYR 在第 9 行进行更改。

import tkinter as tk
from tkinter import ttk
import urllib.request
import json
import time

def get_luno():
    # to change ticker pair, look at here https://api.mybitx.com/api/1/tickers
    req = urllib.request.urlopen("https://api.mybitx.com/api/1/ticker?pair=XBTMYR")
    x = json.loads(req.read().decode("utf-8"))
    req.close()
    return x

def refresh_price():
    aLable.configure(text="Ask price: RM " + get_luno()["ask"])
    bLable.configure(text="Time: " + 
        str(time.strftime("%Y-%m-%d %H:%M:%S", 
        time.gmtime(get_luno()["timestamp"]/1000 + 28800))))

win = tk.Tk()
win.title("Bitcoin price in MYR")

aLable = ttk.Label(win, text="Ask price: RM " + get_luno()["ask"])
aLable.grid(column=0, row=0, padx=8, pady=4)

bLable = ttk.Label(text="Time: " + 
        str(time.strftime("%Y-%m-%d %H:%M:%S", 
        time.gmtime(get_luno()["timestamp"]/1000 + 28800))))
bLable.grid(column=0, row=1, padx=8, pady=4)

action = ttk.Button(win, text="Refresh", command=refresh_price)
action.grid(column=0, row=2, padx=8, pady=4)

win.mainloop()

37. Codechef 自动提交

一个使用 selenium 在 [ https://www.codechef.com ]上提交代码的简单脚本。

from selenium import webdriver
import getpass
import time

username = "username"
password = getpass.getpass("Password:")

problem = 'TEST'

code = """
#include 

int main(void) {
char c, d=10;
while(std::cin.get(c) && (c!='2' || d!='4') && std::cout.put(d))
d=c;
} 
"""

browser = webdriver.Firefox()

browser.get('https://www.codechef.com')

nameElem = browser.find_element_by_id('edit-name')
nameElem.send_keys(username)

passElem = browser.find_element_by_id('edit-pass')
passElem.send_keys(password)

browser.find_element_by_id('edit-submit').click()

browser.get("https://www.codechef.com/submit/" + problem)

time.sleep(20)

browser.find_element_by_id("edit_area_toggle_checkbox_edit-program").click()

inputElem = browser.find_element_by_id('edit-program')
inputElem.send_keys(code)

browser.find_element_by_id("edit-submit").click()

38. 校验和

该脚本可以从 md5、sha1、sha224、sha256、sha384 和 sha512 生成校验和。此外,对于另一层秘密,它可以使用 HMAC 和提供的秘密创建签名的校验和。最后,为了向脚本提供实际值,它还可以验证校验和是否与其生成的文件匹配。

例子:

生成 sha1 校验和

python checksum.py -H sha1 -f test.txt -g  
# b29d28bc5239dbc2689215811b2a73588609f301

生成签名

python checksum.py -f test.txt -s secret  
# 3YYMCthY4hFxQj1wPF3uAg==

验证校验和

python -H sha1 -f test.txt -v b29d28bc5239dbc2689215811b2a73588609f301

验证签名

python -f test.txt -s secret -v 3YYMCthY4hFxQj1wPF3uAg==
import os
import sys
import hmac
import base64
import hashlib
import argparse

def checksum(hash, seed=None):
    hashs = {
        "md5": hashlib.md5,
        "sha1": hashlib.sha1,
        "sha224": hashlib.sha224,
        "sha256": hashlib.sha256,
        "sha384": hashlib.sha384,
        "sha512": hashlib.sha512
    }
    method = hashs.get(hash, hashlib.md5)()
    if seed is not None:
        method.update(seed.encode("utf-8"))
    else:
        method.update(os.urandom(32))
    return method.hexdigest()

def sign(hash, message, secret):
    hashs = {
        "md5": hashlib.md5,
        "sha1": hashlib.sha1,
        "sha224": hashlib.sha224,
        "sha256": hashlib.sha256,
        "sha384": hashlib.sha384,
        "sha512": hashlib.sha512
    }
    method = hashs.get(hash, hashlib.md5)()
    digest = hmac.new(secret.encode("utf-8"), 
                msg=message.encode(),
                digestmod=hashs.get(hash, hashlib.md5)).digest()
    signature = base64.b64encode(digest).decode("utf-8")
    return signature

def verify(hash, input, check, secret=None):
    challenge = None
    if secret is not None:
        challenge = sign(hash, input, secret)
    else:
        challenge = checksum(hash, input)
    return "Valid! :D" if challenge == check else "Invalid :("

def main():
    description = "Checksum tool to generate, sign, and verify"
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("-g", "--generate", dest="generate", 
        action="store_true", help="Generates checksum")
    parser.add_argument("-s", "--sign", dest="sign", default=None, 
        help="Signs input using HMAC")
    parser.add_argument("-H", "--hash", dest="hash", default="md5",
        help="Hash method (md5, sha1, sha224, sha256, sha384, sha512)")
    parser.add_argument("-v", "--verify", dest="verify", default=None,
        help="Checksum or signature used to verify against file / stdin")
    parser.add_argument("-f", "--file", dest="file", 
        type=argparse.FileType("r"), default=sys.stdin,
        help="File / stdin to create checksum, make signature, or verify from")
    arguments = parser.parse_args()

    if arguments.verify is not None:
        if not arguments.file:
            print("Missing input to generate checksum from")
            sys.exit(1)
        if arguments.sign is not None:
            print(verify(arguments.hash, arguments.file.read(),
                         arguments.verify, arguments.sign))
            return
        else:
            print(verify(arguments.hash, arguments.file.read(),
                         arguments.verify))
            return
    elif arguments.generate:
        if not arguments.file:
            print("Missing input to generate checksum from")
            sys.exit(1)
        print(checksum(arguments.hash, arguments.file.read()))
        return
    elif arguments.sign is not None:
        if not arguments.file:
            print("Missing input to generate checksum from")
            sys.exit(1)
        print(sign(arguments.hash, arguments.file.read(), arguments.sign))
        return
    print("Missing function (-g, -s, -v)")
    sys.exit(1)

if __name__ == "__main__":
    main()

39. 加密货币转换器

使用 PyQt 在 Python 中实现的加密货币转换器的简单 GUI。UI 是使用 Qt Creator 设计的。

要求

Python 3.xx PyQt5 requests

用法

要开始将您的加密货币转换为美元、欧元或其他加密货币,请输入:

$ virtualenv crypto-env  
$ source crypto-env/bin/activate  
$ pip3 install -r requirements.txt  
$ python CryptoConverter.py
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from MainWindow import Ui_MainWindow
import json
import requests


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)
        self.show()
        # Vars
        self.new_label = '0'
        self.cur1 = 'BTC'
        self.cur2 = 'USD'
        self.result = ''
        # Connect buttons
        for n in range(0, 10):
            getattr(self, 'pushButton_n%s' % n).clicked.connect(self.digit_pressed)
        self.pushButton_n10.clicked.connect(self.decimal_point)
        self.pushButton_del.clicked.connect(self.del_digit)
        self.pushButton_convert.clicked.connect(self.convert_fun)
        self.comboBox.activated[str].connect(self.currencies1)
        self.comboBox_2.activated[str].connect(self.currencies2)

    def digit_pressed(self):
        button = self.sender()
        self.new_label = self.label_1.text() + button.text()
        if '.' in self.new_label:
            self.label_1.setText(str(self.new_label))
        else:
            self.label_1.setText(str(int(self.new_label)))

    def decimal_point(self):
        if '.' in self.label_1.text():
            pass
        else:
            self.label_1.setText(self.label_1.text() + '.')

    def del_digit(self):
        self.new_label = self.new_label[:-1]
        self.label_1.setText(self.new_label)

    def currencies1(self, item1):
        self.cur1 = item1
        # print(self.cur1)

    def currencies2(self, item2):
        self.cur2 = item2
        # print(self.cur2)

    # Live data from API
    def api(self, cur1, cur2):
        api_link = "https://min-api.cryptocompare.com/data/pricemulti?fsyms={}&tsyms={}".format(cur1, cur2)
        resp = requests.get(api_link)
        # print(r.status_code)
        data = json.loads(resp.content)
        # print(data)
        var = data[self.cur1][self.cur2]
        return var

    def convert_fun(self):
        try:
            if len(self.new_label) == 0:
                self.label_1.setText('0')
                self.label_2.setText('0')
            if '.' in self.new_label:
                self.result = float(self.new_label) * self.api(self.cur1, self.cur2)
                self.result = round(self.result, 2)
                self.label_2.setText(str(self.result))
            else:
                self.result = int(self.new_label) * self.api(self.cur1, self.cur2)
                self.result = round(self.result, 2)
                self.label_2.setText(str(self.result))
        except (KeyError, ValueError):
            pass
        except requests.exceptions.ConnectionError:
            print('Please verify your internet connection!')


if __name__ == '__main__':
    app = QApplication([])
    app.setApplicationName("CryptoConverter")
    window = MainWindow()
    app.exec_()

40. 加密货币价格

该程序获取加密货币的实时价格。

要求

安装所需的库:

$ pip install requests bs4 colorama

之后运行:

$ python cryptocurrency-prices.py
#!python3
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
from colorama import init, Fore, Back, Style
import sys
import os

#get the price
def get_price():
    #response from the url
    response = requests.get(url)

    #soup object of the html content
    soup = BeautifulSoup(response.content,'html.parser')

    #for bitcoin
    if asset == 'btc':
        price = soup.find('span',{'class':'price'}).text #bitcoin works faster with the price class

    #for other altcoins
    else:
        price = soup.find('span',{'class':'woobJfK-Xb2EM1W1o8yoE'}).text #other altcoins only work with this class

    return float(price.replace(",",""))

#asset choice
asset = input('Abbreviation of the asset: ')
url = 'https://cryptowat.ch/assets/' + asset

#catching the NoneType AttributeError error for coins that cant be found
try:
    price = get_price()

except AttributeError:
    print("The asset doesn't exist or it's not supported!")
    sys.exit()

#visual
if sys.platform == 'win32':
    os.system('cls')
else:
    os.system('clear')

#since the last price must be something from the start its set to 0
price = 0

#loop
while True:

    #getting the price
    last_price = price
    price = get_price()

    #coloring the price according to the change
    if price > last_price:
        color = Fore.GREEN
    elif last_price > price:
        color = Fore.RED
    else:
        color = Style.RESET_ALL

    #printing the price
    print('$ ',end='')
    print(color + str(price) + Style.RESET_ALL)

 汇总连接:

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

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

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

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

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

你可能感兴趣的:(python,开发语言,前端)