ホームページ  >  記事  >  バックエンド開発  >  5 つの興味深い Python スクリプト

5 つの興味深い Python スクリプト

WBOY
WBOY転載
2023-04-12 09:10:041568ブラウズ

Python は、クローラー、予測分析、GUI、自動化、画像処理、視覚化など、さまざまな用途に使用できます。優れた機能を実現するには、わずか数十行のコードしか必要としません。

Python は動的スクリプト言語であるため、コード ロジックは Java よりもはるかに単純で、同じ機能を実現するために必要なコードの量ははるかに少なくなります。さらに、Python エコシステムには、関数をパッケージにカプセル化するサードパーティ ツール ライブラリが多数あり、インターフェイスを呼び出すだけで複雑な関数を使用できます。

ここでは、シンプルで楽しいスクリプトの例をいくつか紹介します。初心者はコードに従って、Python 構文をすぐにマスターできます。

1. PIL、Matplotlib、Numpy を使用してぼやけた古い写真を修復する

5 つの興味深い Python スクリプト

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)


img = np.asarray(img)
flat = img.flatten()


def get_histogram(image, bins):

histogram = np.zeros(bins)

for pixel in image:
histogram[pixel] += 1

return histogram


hist = get_histogram(flat, 256)


cs = np.cumsum(hist)


nj = (cs - cs.min()) * 255
N = cs.max() - cs.min()


cs = nj / N


cs = cs.astype('uint8')


img_new = cs[flat]


img_new = np.reshape(img_new, img.shape)


fig = plt.figure()
fig.set_figheight(15)
fig.set_figwidth(15)


fig.add_subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title("Image 'Before' Contrast Adjustment")


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.show()

2. ファイルをバッチで圧縮し、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}')

3. tkinter を使用して電卓 GUI を作成する

tkinter は Python 独自の GUI ライブラリであり、初心者が小さなソフトウェアを作成する練習に適しています

import tkinter as tk

root = tk.Tk()
root.title("Standard Calculator")
root.resizable(0, 0)


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):
temp = e.get(
)
e.delete(0, tk.END)
e.insert(0, temp + num)


def buttonClear():
e.delete(0, tk.END)

4. PDF を Word ファイルに変換する

pdf2docx ライブラリを使用して PDF ファイルを Word 形式に変換します

5 つの興味深い Python スクリプト

from pdf2docx import Converter
import os 
import sys


pdf = input("Enter the path to your file: ")
assert os.path.exists(pdf), "File not found at, "+str(pdf)
f = open(pdf,'r+')


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

doc_name = input("Enter the custom name : ")+".docx"

else:


pdf_name = os.path.basename(pdf)

doc_name =os.path.splitext(pdf_name)[0] + ".docx"



cv = Converter(pdf)


path = os.path.dirname(pdf)

cv.convert(os.path.join(path, "", doc_name) , start=0, end=None)
print("Word doc created!")
cv.close()

5. Python は自動的に電子メールを送信します

これは、smtplib と smtplib を使用して実現できます。電子メール ライブラリ スクリプトは電子メールを送信します。

5 つの興味深い Python スクリプト

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


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 = """你好,这是一个测试邮件!"""

message_text = MIMEText(body_content,"plain","utf-8")

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)


stp = smtplib.SMTP()

stp.connect(mail_host, 25)

stp.set_debuglevel(1)

stp.login(mail_sender,mail_license)

stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")

stp.quit()

概要

Python には、楽しい小さなスクリプトもたくさんあります。独自のシナリオに従ってそれらを作成することも、既製のサードパーティライブラリを使用します。

以上が5 つの興味深い Python スクリプトの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事は51cto.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。