本文介绍: 【代码】50个常用Python脚本

50个常用Python脚本代码示例

  1. 复制文件目录
import shutil
shutil.copy2('source_file', 'destination')
shutil.copytree('source_dir', 'destination')
  1. 字符串替换查找
import re
string = "hello world"
new_string = re.sub(r"world", "python", string)
print(new_string)

if "world" in new_string:
  print("Found")
else:
  print("Not found")
  1. 文件读写操作
with open("file.txt", "r") as file:
  data = file.read()

with open("file.txt", "a") as file:
  file.write("New content")
  1. 解析CSV文件
import csv
with open('file.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in reader:
        print(', '.join(row))
  1. 解析Excel文件
import xlrd
workbook = xlrd.open_workbook('file.xlsx')
sheet = workbook.sheet_by_index(0)
print(sheet.cell_value(0, 0))
  1. 计算日期时间
from datetime import datetime, timedelta
now = datetime.now()
today = datetime.today()
tomorrow = today + timedelta(days=1)
  1. 生成随机数
import random
random_number = random.randint(1, 100)
  1. 判断两个文件是否相同
import filecmp
if filecmp.cmp('file1.txt', 'file2.txt'):
    print("The files are the same")
else:
    print("The files are different")
  1. 命令行读取参数
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input", help="input file name")
args = parser.parse_args()
print(args.input)
  1. 定时执行脚本
import time
while True:
    print("Hello")
    time.sleep(1) # wait for 1 second
  1. 发送电子邮件
import smtplib
from email.mime.text import MIMEText

msg = MIMEText('This is the body of the email')
msg['Subject'] = 'Subject'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'

s = smtplib.SMTP('localhost')
s.sendmail('sender@example.com', ['recipient@example.com'], msg.as_string())
s.quit()
  1. 使用正则表达式匹配字符串
import re
match = re.search(r"world", "hello world")
print(match.group())
  1. 使用JSON格式处理数据
import json
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
json_string = json.dumps(data)
new_data = json.loads(json_string)
  1. 解析XML文件
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
print(root.tag)
  1. 将PDF转换成文本文
import PyPDF2
pdf_file = open('file.pdf', 'rb')
reader = PyPDF2.PdfReader(pdf_file)
text = ""
for page in reader.pages:
    text += page.text
  1. 爬取网页内容
import requests
response = requests.get('http://example.com')
print(response.content)
  1. 获取本机IP地址
import socket
print(socket.gethostbyname(socket.gethostname()))
  1. 生成二维码
import qrcode
img = qrcode.make('Hello, World!')
img.save('qrcode.png')
  1. 计算文件大小
import os
size = os.path.getsize('file.txt')
  1. 图片进行处理
from PIL import Image
img = Image.open('image.jpg')
img = img.resize((400, 300))
img.save('new_image.jpg')
  1. 反转字符串
string = "hello world"
new_string = string[::-1]
print(new_string)
  1. 计算字符串单词的数量
string = "hello world"
word_count = len(string.split())
print(word_count)
  1. 模糊匹配字符串
from fuzzywuzzy import fuzz
ratio = fuzz.ratio("hello world", "helloworld")
print(ratio)
  1. 显示进度条
import time
from tqdm import tqdm
for i in tqdm(range(100)):
    time.sleep(0.1)
  1. 创建ZIP文件
import zipfile
with zipfile.ZipFile('file.zip', 'w') as zip:
    zip.write('file.txt')
  1. 使用FTP上传下载文件
import ftplib
ftp = ftplib.FTP()
ftp.connect('ftp.example.com')
ftp.login('username', 'password')
ftp.cwd('/uploads')
with open('file.txt', 'rb') as file:
    ftp.storbinary('STOR file.txt', file)
ftp.quit()
  1. 通过网络发送广播消息
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(b'Hello, World!', ('<broadcast>', 12345))
s.close()
  1. 控制键盘鼠标
import pyautogui
pyautogui.moveTo(100, 100, duration=1)
pyautogui.click(button='left')
  1. 剪贴板操作
import pyperclip
text = pyperclip.paste()
pyperclip.copy('New text')
  1. 创建管理日志文件
import logging

logging.basicConfig(filename='app.log', level=logging.INFO)

logging.debug('This is a debug message')
logging.info('This is an informational message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
  1. 打印统信
import platform
print(platform.system())
print(platform.release())
  1. 投掷骰子模拟游戏
import random
class Dice:
    def throw(self):
        return random.randint(1, 6)

dice = Dice()
result = dice.throw()
print(result)
  1. 编写简单计算器
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

a = 5
b = 3
print(add(a, b))
print(subtract(a, b))
print(multiply(a, b))
print(divide(a, b))
  1. 处理异常错误
try:
    x = 1 / 0
except ZeroDivisionError as e:
    print(e)
finally:
    print("Finally block")
  1. 生成缩略图
from PIL import Image
img = Image.open('image.jpg')
img.thumbnail((100, 100))
img.save('thumbnail.jpg')
  1. 使用Google Maps API获取地图数据
import requests
response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')
json_data = response.json()
lat = json_data['results'][0]['geometry']['location']['lat']
lng = json_data['results'][0]['geometry']['location']['lng']
  1. 调用外部命令
import os
os.system('ls -l')
  1. 使用subprocess模块启动后台任务
import subprocess
subprocess.Popen(['python', 'script.py'])
  1. 爬虫去重
from collections import defaultdict
url_list = ['http://example.com', 'http://example.com', 'http://google.com']
url_dict = defaultdict(int)
for url in url_list:
    url_dict[url] += 1
print(url_dict.keys())
  1. 自动化微信账号管理
import itchat

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return "I received: " + msg.text

itchat.auto_login(hotReload=True)
itchat.run()
  1. 简单聊天机器人
import random

responses = ["Hello", "Hi", "How are you?", "I'm fine.", "Goodbye"]

while True:
    message = input("You: ")
    if message == "exit":
        break
    response = random.choice(responses)
    print("Bot: " + response)
  1. 查找最大值最小值
numbers = [1, 2, 3, 4, 5]
print(max(numbers))
print(min(numbers))
  1. 字符串转换为Python代码执行
code = """
for i in range(10):
    print(i)
"""
exec(code)
  1. 生成二进制文件
with open("file.bin", "wb") as file:
    data = bytes([0x01, 0x02, 0x03])
    file.write(data)
  1. 数据清洗和处理
import pandas as pd
data = pd.read_csv('file.csv')
data = data.dropna() # remove null values
data = data.sort_values('column') # sort by column
  1. 实现FTP服务器
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()
authorizer.add_anonymous('/')

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(('localhost', 21), handler)
server.serve_forever()
  1. 数据库连接查询操作
import sqlite3
connection = sqlite3.connect('example.db')
cursor = connection.cursor()

cursor.execute("CREATE TABLE example (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO example (name) VALUES ('John')")
data = cursor.execute("SELECT * FROM example")
for row in data:
    print(row)

connection.close()
  1. 实现简单的Web服务器
from http.server import HTTPServer, BaseHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        message = "Hello, World!"
        self.wfile.write(bytes(message, "utf8"))

httpd = HTTPServer(('localhost', 8080), MyHandler)
httpd.serve_forever()
  1. 使用Python实现加密算法
import hashlib
message = "Hello, World!"
hash_object = hashlib.sha256(message.encode('utf-8'))
hash_value = hash_object.hexdigest()
print(hash_value)
  1. 实现基本人工智能
import random
responses = {
    "hello": ["Hello", "Hi", "How are you?"],
    "goodbye": ["Goodbye", "See you later", "Take care"]
}

while True:
    message = input("You: ")
    if message == "exit":
        break
    for keyword in responses.keys():
        if keyword in message.lower():
            response = random.choice(responses[keyword])
            print("Bot: " + response)
            break
    else:
        print("Bot: Sorry, I don't understand.")

以上是50个常用Python脚

原文地址:https://blog.csdn.net/m0_55877125/article/details/130041895

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_18157.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注