1.使用 Python 进行速度测试
这个高级脚本帮助你使用 Python 测试你的 Internet 速度。只需安装速度测试模块并运行以下代码。
# pip install pyspeedtest
# pip install speedtest
# pip install speedtest-cli
#method 1
import speedtest
speedTest = speedtest.Speedtest()
print(speedTest.get_best_server())
#Check download speed
print(speedTest.download())
#Check upload speed
print(speedTest.upload())
# Method 2
import pyspeedtest
st = pyspeedtest.SpeedTest()
st.ping()
st.download()
st.upload()
2.在谷歌上搜索
你可以从 Google 搜索引擎中提取重定向 URL,安装以下提及模块并遵循代码。
# pip install google
from googlesearch import search
query = "Medium.com"
for url in search(query):
print(url)
3.制作网络机器人
该脚本将帮助你使用 Python 自动化网站。你可以构建一个可控制任何网站的网络机器人。查看下面的代码,这个脚本在网络抓取和网络自动化中很方便。
# pip install selenium
import time
from selenium import webdriver
from selenium.webdriver.common.keys
import Keysbot = webdriver.Chrome("chromedriver.exe")
bot.get('http://www.google.com')
search = bot.find_element_by_name('q')
search.send_keys("@codedev101")
search.send_keys(Keys.RETURN)
time.sleep(5)
bot.quit()
4.获取歌曲歌词
这个高级脚本将向你展示如何从任何歌曲中获取歌词。首先,你必须从 Lyricsgenius 网站获得免费的 API 密钥,然后,你必须遵循以下代码。
# pip install lyricsgenius
import lyricsgenius
api_key = "xxxxxxxxxxxxxxxxxxxxx"
genius = lyricsgenius.Genius(api_key)
artist = genius.search_artist("Pop Smoke",
max_songs=5,sort="title")
song = artist.song("100k On a Coupe")
print(song.lyrics)
5.获取照片的Exif数据
使用 Python Pillow 模块获取任何照片的 Exif 数据。查看下面提到的代码。我提供了两种方法来提取照片的 Exif 数据。
# Get Exif of Photo
# Method 1
# pip install pillow
import PIL.Image
import PIL.ExifTags
img = PIL.Image.open("Img.jpg")
exif_data =
{
PIL.ExifTags.TAGS[i]: j
for i, j in img._getexif().items()
if i in PIL.ExifTags.TAGS
}
print(exif_data)
# Method 2
# pip install ExifRead
import exifread
filename = open(path_name, 'rb')
tags = exifread.process_file(filename)
print(tags)
6.提取图像中的 OCR 文本
OCR 是一种从数字和扫描文档中识别文本的方法。许多开发人员使用它来读取手写数据,下面的 Python 代码可以将扫描的图像转换为 OCR 文本格式。
注意:你必须从 Github 下载 tesseract.exe
# pip install pytesseract
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
t=Image.open("img.png")
text = pytesseract.image_to_string(t, config='')
print(text)
7.将照片转换为Cartonize
这个简单的高级脚本会将你的照片转换为 Cartonize 格式。查看下面的示例代码并尝试一下。
# pip install opencv-python
import cv2
img = cv2.imread('img.jpg')
grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grayimg = cv2.medianBlur(grayimg, 5)
edges = cv2.Laplacian(grayimg , cv2.CV_8U, ksize=5)
r,mask =cv2.threshold(edges,100,255,cv2.THRESH_BINARY_INV)
img2 = cv2.bitwise_and(img, img, mask=mask)
img2 = cv2.medianBlur(img2, 5)
cv2.imwrite("cartooned.jpg", mask)
8.清空回收站
这个简单的脚本可以让你用 Python 清空你的回收站,查看下面的代码以了解如何操作。
# pip install winshell
import winshell
try:
winshell.recycle_bin().empty(confirm=False, /show_progress=False, sound=True)
print("Recycle bin is emptied Now")
except:
print("Recycle bin already empty")
9.Python 图像增强
使用 Python Pillow 库增强你的照片以使其看起来更好。在下面的代码中,我实现了四种方法来增强任何照片。
# pip install pillow
from PIL import Image,ImageFilter
from PIL import ImageEnhance
im = Image.open('img.jpg')
# Choose your filter
# add Hastag at start if you don't want to any filter below
en = ImageEnhance.Color(im)
en = ImageEnhance.Contrast(im)
en = ImageEnhance.Brightness(im)
en = ImageEnhance.Sharpness(im)# result
en.enhance(1.5).show("enhanced")
10.获取 Window 版本
这个简单的脚本将帮助你获得当前使用的完整窗口版本。
# Window Versionimport wmi
data = wmi.WMI()
for os_name in data.Win32_OperatingSystem():
print(os_name.Caption)
# Microsoft Windows 11 Home
11.将 PDF 转换为图像
使用以下代码将所有 Pdf 页转换为图像。
# PDF to Images
import fitz
pdf = 'sample_pdf.pdf'
doc = fitz.open(pdf)
for page in doc:
pix = page.getPixmap(alpha=False)
pix.writePNG('page-%i.png' % page.number)
12.转换:十六进制到 RGB
该脚本将简单地将 Hex 转换为 RGB。查看下面的示例代码。
# Conversion: Hex to RGB
def Hex_to_Rgb(hex):
h = hex.lstrip('#')
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
print(Hex_to_Rgb('#c96d9d')) # (201, 109, 157)
print(Hex_to_Rgb('#fa0515')) # (250, 5, 21)
13.网站状态
你可以使用 Python 检查网站是否正常运行。检查以下代码,显示200 ,表示网站已启动,如果显示为 404 ,则表示网站已关闭。
# pip install requests
#method 1
import urllib.request
from urllib.request import Request, urlopenreq = Request('https://medium.com/@pythonians', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).getcode()
print(webpage) # 200
# method 2
import requests
r = requests.get("https://medium.com/@pythonians")
print(r.status_code) # 200
14.使用PIL、Matplotlib、Numpy对模糊老照片进行修复
# encoding=utf-8
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os.path
# 读取图片
img_path = "E:\\test.jpg"
img = Image.open(img_path)
# 图像转化为numpy数组
img = np.asarray(img)
flat = img.flatten()
# 创建函数
def get_histogram(image, bins):
# array with size of bins, set to zeros
histogram = np.zeros(bins)
# loop through pixels and sum up counts of pixels
for pixel in image:
histogram[pixel] += 1
# return our final result
return histogram
# execute our histogram function
hist = get_histogram(flat, 256)
# execute the fn
cs = np.cumsum(hist)
# numerator & denomenator
nj = (cs - cs.min()) * 255
N = cs.max() - cs.min()
# re-normalize the cumsum
cs = nj / N
# cast it back to uint8 since we can't use floating point values in images
cs = cs.astype('uint8')
# get the value from cumulative sum for every index in flat, and set that as img_new
img_new = cs[flat]
# put array back into original shape since we flattened it
img_new = np.reshape(img_new, img.shape)
# set up side-by-side image display
fig = plt.figure()
fig.set_figheight(15)
fig.set_figwidth(15)
# display the real image
fig.add_subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title("Image 'Before' Contrast Adjustment")
# display the new image
fig.add_subplot(1, 2, 2)
plt.imshow(img_new, cmap='gray')
plt.title("Image 'After' Contrast Adjustment")
filename = os.path.basename(img_path)
# plt.savefig("E:\\" + filename)
plt.show()
15.将文件批量压缩,使用zipfile库
import os
import zipfile
from random import randrange
def zip_dir(path, zip_handler):
for root, dirs, files in os.walk(path):
for file in files:
zip_handler.write(os.path.join(root, file))
if __name__ == '__main__':
to_zip = input("""
Enter the name of the folder you want to zip
(N.B.: The folder name should not contain blank spaces)
>
""")
to_zip = to_zip.strip() + "/"
zip_file_name = f'zip{randrange(0,10000)}.zip'
zip_file = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
zip_dir(to_zip, zip_file)
zip_file.close()
print(f'File Saved as {zip_file_name}')
16.使用tkinter制作计算器GUI
tkinter是python自带的GUI库,适合初学者练手创建小软件
import tkinter as tk
root = tk.Tk() # Main box window
root.title("Standard Calculator") # Title shown at the title bar
root.resizable(0, 0) # disabling the resizeing of the window
# Creating an entry field:
e = tk.Entry(root,
width=35,
bg='#f0ffff',
fg='black',
borderwidth=5,
justify='right',
font='Calibri 15')
e.grid(row=0, column=0, columnspan=3, padx=12, pady=12)
def buttonClick(num): # function for clicking
temp = e.get(
) # temporary varibale to store the current input in the screen
e.delete(0, tk.END) # clearing the screen from index 0 to END
e.insert(0, temp + num) # inserting the incoming number input
def buttonClear(): # function for clearing
e.delete(0, tk.END)
# 代码过长,部分略
17.PDF转换为Word文件
使用pdf2docx库,可以将PDF文件转为Word格式
from pdf2docx import Converter
import os
import sys
# Take PDF's path as input
pdf = input("Enter the path to your file: ")
assert os.path.exists(pdf), "File not found at, "+str(pdf)
f = open(pdf,'r+')
#Ask for custom name for the word doc
doc_name_choice = input("Do you want to give a custom name to your file ?(Y/N)")
if(doc_name_choice == 'Y' or doc_name_choice == 'y'):
# User input
doc_name = input("Enter the custom name : ")+".docx"
else:
# Use the same name as pdf
# Get the file name from the path provided by the user
pdf_name = os.path.basename(pdf)
# Get the name without the extension .pdf
doc_name = os.path.splitext(pdf_name)[0] + ".docx"
# Convert PDF to Word
cv = Converter(pdf)
#Path to the directory
path = os.path.dirname(pdf)
cv.convert(os.path.join(path, "", doc_name) , start=0, end=None)
print("Word doc created!")
cv.close()
18.Python自动发送邮件
使用smtplib和email库可以实现脚本发送邮件
import smtplib
import email
# 负责构造文本
from email.mime.text import MIMEText
# 负责构造图片
from email.mime.image import MIMEImage
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.header import Header
# SMTP服务器,这里使用163邮箱
mail_host = "smtp.163.com"
# 发件人邮箱
mail_sender = "******@163.com"
# 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程
mail_license = "********"
# 收件人邮箱,可以为多个收件人
mail_receivers = ["******@qq.com","******@outlook.com"]
mm = MIMEMultipart('related')
# 邮件主题
subject_content = """Python邮件测试"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "sender_name<******@163.com>"
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "receiver_1_name<******@qq.com>,receiver_2_name<******@outlook.com>"
# 设置邮件主题
mm["Subject"] = Header(subject_content,'utf-8')
# 邮件正文内容
body_content = """你好,这是一个测试邮件!"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)
# 二进制读取图片
image_data = open('a.jpg','rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
mm.attach(message_image)
# 构造附件
atta = MIMEText(open('sample.xlsx', 'rb').read(), 'base64', 'utf-8')
# 设置附件信息
atta["Content-Disposition"] = 'attachment; filename="sample.xlsx"'
# 添加附件到邮件信息当中去
mm.attach(atta)
# 创建SMTP对象
stp = smtplib.SMTP()
# 设置发件人邮箱的域名和端口,端口地址为25
stp.connect(mail_host, 25)
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(mail_sender,mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")
# 关闭SMTP对象
stp.quit()
19.Jpg转Png
图片格式转换,以前小F可能第一时间想到的是【格式工厂】这个软件。
如今编写一个Python脚本就能完成各种图片格式的转换,此处以jpg转成png为例。
有两种解决方法,都分享给大家。
# 图片格式转换, Jpg转Png
# 方法①
from PIL import Image
img = Image.open('test.jpg')
img.save('test1.png')
# 方法②
from cv2 import imread, imwrite
image = imread("test.jpg", 1)
imwrite("test2.png", image)
20.PDF加密和解密
如果你有100个或更多的PDF文件需要加密,手动进行加密肯定是不可行的,极其浪费时间。
使用Python的pikepdf模块,即可对文件进行加密,写一个循环就能进行批量加密文档。
# PDF加密
import pikepdf
pdf = pikepdf.open("test.pdf")
pdf.save('encrypt.pdf', encryption=pikepdf.Encryption(owner="your_password", user="your_password", R=4))
pdf.close()
有加密那么便会有解密,代码如下。
# PDF解密
import pikepdf
pdf = pikepdf.open("encrypt.pdf", password='your_password')
pdf.save("decrypt.pdf")
pdf.close()