Python 基础案例
- 数据类型
整数(int)
浮点数(float)
字符串(str)
布尔值(bool)
- 注释
单行注释
# 这是单行注释
多行注释
"""
这是
多行注释
"""
- 算术运算
a + b # 加法
a - b # 减法
a * b # 乘法
a / b # 除法
a % b # 取余
a ** b # 幂运算
- 加法和减法函数
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# 测试函数
print("加法: 5 + 3 =", add(5, 3))
print("减法: 5 - 3 =", subtract(5, 3))
- 比较运算
a == b # 等于
a != b # 不等于
a > b # 大于
a < b # 小于
a >= b # 大于等于
a <= b # 小于等于
- 捕获异常
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Error: Division by zero is not allowed."
# 测试函数
print(divide(10, 2))
print(divide(10, 0))
7.九九乘法表
def print_multiplication_table():
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j} * {i} = {j * i}", end="\t")
print()
# 调用函数打印乘法表
print_multiplication_table()
- 逻辑运算
a and b
a or b
not a
- 条件语句
if condition:
# do something
elif another_condition:
# do something else
else:
# do something different
10.打印空心菱形
def print_hollow_diamond(size):
# 打印上半部分
for i in range(size):
for j in range(size - i):
print(" ", end="")
for k in range(2 * i + 1):
if k == 0 or k == 2 * i:
print("*", end="")
else:
print(" ", end="")
print()
# 打印下半部分
for i in range(size - 2, -1, -1):
for j in range(size - i):
print(" ", end="")
for k in range(2 * i + 1):
if k == 0 or k == 2 * i:
print("*", end="")
else:
print(" ", end="")
print()
# 设置菱形大小
size = 5
print_hollow_diamond(size)
输出结果
*
* *
* *
* *
* *
* *
* *
* *
*
- 循环
for 循环
for i in range(5):
print(i)
while 循环
while condition:
# do something
- 列表
list = [1, 2, 3]
list.append(4)
list[0] # 访问元素
- 元组
tuple = (1, 2, 3)
- 字典
dict = {"name": "namdala", "age": 30}
dict["name"] # 访问键值
- 集合
my_set = {1, 2, 3}
my_set.add(4)
- 字符串操作
s = "hello"
s.upper()
s.lower()
s.split(" ")
s.replace("h", "j")
17. 字符串格式化
name = "mandala"
age = 30
f"Hello, {name}. You are {age}."
- 列表解析
squares = [x**2 for x in range(10)]
- 函数定义
def my_function(param1, param2):
return param1 + param2
20. 默认参数
def my_function(param1, param2=5):
return param1 + param2
- 关键字参数
def my_function(param1, param2):
return param1 + param2
my_function(param2=10, param1=5)
- 可变参数
def my_function(*args):
for arg in args:
print(arg)
my_function(1, 2, 3)
- 关键字可变参数
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_function(name="mandala", age=18)
- lambda表达式
f = lambda x: x**2
f(5)
- map函数
list(map(lambda x: x**2, range(10)))
- filter函数
list(filter(lambda x: x % 2 == 0, range(10)))
- reduce函数
from functools import reduce
reduce(lambda x, y: x + y, range(10))
- 异常处理
try:
# do something
except Exception as e:
print(e)
finally:
# cleanup
- 文件读取
with open("file.txt", "r") as file:
content = file.read()
- 文件写入
with open("file.txt", "w") as file:
file.write("Hello, World!")
- 类定义
class MyClass:
def __init__(self, param1):
self.param1 = param1
def my_method(self):
return self.param1
- 类继承
class MyBaseClass:
def __init__(self, param1):
self.param1 = param1
class MyDerivedClass(MyBaseClass):
def __init__(self, param1, param2):
super().__init__(param1)
self.param2 = param2
- 魔法方法
class MyClass:
def __init__(self, param1):
self.param1 = param1
def __str__(self):
return f"MyClass with param1={self.param1}"
- 属性和装饰器
class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value
- 生成器
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
- 列表解析和生成器表达式
[x**2 for x in range(10)]
(x**2 for x in range(10))
- 集合解析
{x**2 for x in range(10)}
- 字典解析
{x: x**2 for x in range(10)}
- 上下文管理器
with open("file.txt", "r") as file:
content = file.read()
- 装饰器
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def my_function():
print("Function call")
my_function()
- 类型注解
def my_function(param1: int, param2: str) -> str:
return param2 * param1
- 枚举
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
- 迭代器
class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
- JSON解析
import json
json_str = '{"name": "John", "age": 30}'
data = json.loads(json_str)
- 日期和时间
from datetime import datetime
now = datetime.now()
- 随机数生成
import random
random_number = random.randint(1, 10)
- 数学运算
import math
math.sqrt(16)
- 模块和包
# my_module.py
def my_function():
return "Hello"
# main.py
import my_module
my_module.my_function()
- 命名空间
global_var = 5
def my_function():
local_var = 10
global global_var
global_var = 20
- 继承和多态
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
- 操作系统交互
import os
os.getcwd()
os.listdir(".")
- 命令行参数
import sys
for arg in sys.argv:
print(arg)
- 正则表达式
import re
pattern = r"\d+"
re.findall(pattern, "There are 2 apples and 5 bananas.")
通过这些基础知识,你可以快速掌握编程的核心概念和常见操作,适用于大多数编程任务和项目。希望这篇博客对你有所帮助!
- 迭代工具
from itertools import permutations, combinations
list(permutations([1, 2, 3]))
list(combinations([1, 2, 3], 2))
- 默认字典
from collections import defaultdict
d = defaultdict(int)
d["key"] += 1
52. 计数器
from collections import Counter
c = Counter([1, 2, 2, 3, 3, 3])
c.most_common(2)
53. 命名元组
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
p.x, p.y
54. 队列
from collections import deque
d = deque([1, 2, 3])
d.append(4)
d.popleft()
55. 函数工具
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, 2)
double(5)
56. 文档字符串
def my_function():
"""
This is a docstring.
"""
pass
print(my_function.__doc__)
57. 动态属性
class MyClass:
def __init__(self):
self._dynamic = {}
def __getattr__(self, name):
return self._dynamic.get(name, None)
def __setattr__(self, name, value):
if name.startswith("_"):
super().__setattr__(name, value)
else:
self._dynamic[name] = value
58. 类型检查
def my_function(param: int) -> bool:
return isinstance(param, int)
59. 类型别名
from typing import List
Vector = List[float]
60. 数据类
from dataclasses import dataclass
@dataclass
class MyDataClass:
name: str
age: int
61. 枚举成员
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED.name)
print(Color.RED.value)
62. 基本的图像处理
from PIL import Image
img = Image.open("example.jpg")
img = img.convert("L")
img.save("example_gray.jpg")
63. 网络请求
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
64. Web框架 - Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, World!"
if __name__ == '__main__':
app.run()
65. 数据库连接 - SQLite
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS my_table (id INTEGER PRIMARY KEY, name TEXT)''')
conn.commit()
conn.close()
66. 数据库连接 - MySQL
import mysql.connector
conn = mysql.connector.connect(user='user', password='password', host='127.0.0.1', database='test')
cursor = conn.cursor()
cursor.execute('SELECT * FROM my_table')
rows = cursor.fetchall()
conn.close()
67. 数据库ORM - SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///example.db')
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
name = Column(String)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
new_entry = MyTable(name="John")
session.add(new_entry)
session.commit()
68. 并行编程 - 线程
import threading
def print_numbers():
for i in range(5):
print(i)
t = threading.Thread(target=print_numbers)
t.start()
t.join()
69. 并行编程 - 进程
from multiprocessing import Process
def print_numbers():
for i in range(5):
print(i)
p = Process(target=print_numbers)
p.start()
p.join()
70. 并发编程 - asyncio
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(say_hello())
71. 异步I/O - aiohttp
import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
url = 'https://api.example.com/data'
response = asyncio.run(fetch(url))
print(response)
72. 单元测试
import unittest
class TestMyFunction(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
if __name__ == '__main__':
unittest.main()
73. 测试框架 - pytest
def add(x, y):
return x + y
def test_add():
assert add(1, 1) == 2
74. Mock 对象
from unittest.mock import MagicMock
mock = MagicMock()
mock.some_method.return_value = 42
print(mock.some_method())
75. 参数化测试
import pytest
@pytest.mark.parametrize("input,expected", [(1, 2), (2, 3), (3, 4)])
def test_add(input, expected):
assert input + 1 == expected
76. 环境变量
import os
os.environ['MY_ENV_VAR'] = 'value'
print(os.getenv('MY_ENV_VAR'))
77. 配置文件
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config['DEFAULT']['setting'])
78. 日志记录
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This is a debug message')
79. 命令行接口 - argparse
import argparse
parser = argparse.ArgumentParser(description='Example script.')
parser.add_argument('name', type=str, help='Your name')
args = parser.parse_args()
print(f'Hello, {args.name}!')
80. 调试
import pdb
def add(x, y):
pdb.set_trace()
return x + y
add(1, 2)
81. C 扩展
# my_module.c
#include <.h>
static PyObject* my_function(PyObject* self, PyObject* args) {
int x, y;
if (!PyArg_ParseTuple(args, "ii", &x, &y))
return NULL;
return PyLong_FromLong(x + y);
}
static PyMethodDef MyMethods[] = {
{"my_function", my_function, METH_VARARGS, "Add two numbers"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef mymodule = {
PyModuleDef_HEAD_INIT,
"my_module",
NULL,
-1,
MyMethods
};
PyMODINIT_FUNC PyInit_my_module(void) {
return PyModule_Create(&mymodule);
}
82. 扩展模块的构建
# setup.py
from setuptools import setup, Extension
module = Extension('my_module', sources=['my_module.c'])
setup(name='MyModule',
version='1.0',
description='This is a demo package',
ext_modules=[module])
83. 序列化 - pickle
import pickle
data = {'key': 'value'}
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
with open('data.pkl', 'rb') as f:
loaded_data = pickle.load(f)
84. Excel 处理 - openpyxl
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A1'] = "Hello, World!"
wb.save('example.xlsx')
85. PDF 处理 - PyPDF2
import PyPDF2
with open('example.pdf', 'rb') as f:
reader = PyPDF2.PdfFileReader(f)
page = reader.getPage(0)
print(page.extract_text())
86. 图表绘制 - matplotlib
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
87. 数据分析 - pandas
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(df)
88. 数值计算 - numpy
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)
89. 机器学习 - scikit-learn
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit([[1], [2], [3]], [4, 5, 6])
print(model.predict([[4]]))
90. 神经网络 - TensorFlow
import tensorflow as tf
model = tf.keras.Sequential([tf.keras.layers.Dense(10, activation='relu'), tf.keras.layers.Dense(1)])
model.compile(optimizer='adam', loss='mean_squared_error')
91. 图像处理 - OpenCV
import cv2
img = cv2.imread('example.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('example_gray.jpg', gray)
92. 网络爬虫 - BeautifulSoup
from bs4 import BeautifulSoup
import requests
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.text)
93. 自动化浏览器 - Selenium
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://example.com')
print(driver.title)
driver.quit()
94. 电子邮件发送
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'] = 'receiver@example.com'
with smtplib.SMTP('smtp.example.com') as server:
server.login('username', 'password')
server.send_message(msg)
95. 加密与解密 - hashlib
import hashlib
hash_object = hashlib.sha256(b'Hello, World!')
hex_dig = hash_object.hexdigest()
print(hex_dig)
96. 隐写术 - steganography
from stegano import lsb
lsb.hide('input_image.png', message='Secret message').save('output_image.png')
hidden_message = lsb.reveal('output_image.png')
print(hidden_message)
97. 网络编程 - socket
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.example.com', 80))
s.sendall(b'GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n')
response = s.recv(1024)
print(response)
s.close()
98. 并行处理 - concurrent.futures
from concurrent.futures import ThreadPoolExecutor
def task(n):
return n * 2
with ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(task, range(5)))
print(results)
99. 数据校验 - cerberus
from cerberus import Validator
schema = {'name': {'type': 'string'}, 'age': {'type': 'integer'}}
v = Validator(schema)
print(v.validate({'name': 'John', 'age': 30}))
100. 配置管理 - dotenv
from dotenv import load_dotenv
import os
load_dotenv()
print(os.getenv('MY_ENV_VAR'))
101. 项目管理 - poetry
bash
# poetry 安装
curl -sSL https://raw.githubusercontent.com/-poetry/poetry/master/get-poetry.py | -
# 创建项目
poetry new my_project
cd my_project
# 添加依赖
poetry add requests
# 运行项目
poetry run my_project.py
102. 编写 REST API - FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
103. 创建虚拟环境 - venv
bash
# 创建虚拟环境
-m venv myenv
# 激活虚拟环境
source myenv/bin/activate # Unix/macOS
myenv\Scripts\activate # Windows
104. 包管理 - pip
# 安装包
pip install requests
# 列出已安装的包
pip list
# 升级包
pip install --upgrade requests
# 卸载包
pip uninstall requests
105. 跟踪代码 - git
# 初始化仓库
git init
# 添加文件
git add .
# 提交更改
git commit -m "Initial commit"
# 连接远程仓库
git remote add origin https://github.com/username/repo.git
# 推送更改
git push -u origin master
106. 生成文档 - Sphinx
# 安装Sphinx
pip install sphinx
# 初始化Sphinx项目
sphinx-quickstart
# 构建文档
make html
107. 静态类型检查 - mypy
# my_module.py
def add(x: int, y: int) -> int:
return x + y
# 检查类型
mypy my_module.py
108. 代码格式化 - black
# 安装black
pip install black
# 格式化代码
black my_module.py
109. 代码检查 - flake8
# 安装flake8
pip install flake8
# 检查代码
flake8 my_module.py
110. 性能分析 - cProfile
import cProfile
def my_function():
return sum(range(100000))
cProfile.run('my_function()')
111. 内存分析 - memory_profiler
from memory_profiler import profile
@profile
def my_function():
return [i for i in range(100000)]
my_function()
112. 代码热重载 - watchgod
from watchgod import watch
for changes in watch('my_project'):
print(changes)
113. 数据可视化 - seaborn
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips)
plt.show()
114. 统计分析 - statsmodels
import statsmodels.api as sm
data = sm.datasets.get_rdataset("Guerry", "HistData").data
model = sm.OLS(data['Lottery'], sm.add_constant(data['Literacy'])).fit()
print(model.summary())
115. 大数据处理 - Dask
import dask.array as da
arr = da.random.random((10000, 10000), chunks=(1000, 1000))
print(arr.mean().compute())
116. 自然语言处理 - NLTK
import nltk
nltk.download('punkt')
tokens = nltk.word_tokenize("Hello, world!")
print(tokens)
117. 深度学习 - PyTorch
import torch
x = torch.tensor([1.0, 2.0, 3.0])
print(x + 2)
118. 机器人框架 - Rasa
# 安装Rasa
pip install rasa
# 初始化项目
rasa init
# 训练模型
rasa train
# 启动服务
rasa run
119. 语音识别 - SpeechRecognition
import speech_recognition as sr
recognizer = sr.Recognizer()
with sr.Microphone() as source:
audio = recognizer.listen(source)
text = recognizer.recognize_google(audio)
print(text)
121. 文本转语音 - pyttsx3
import pyttsx3
engine = pyttsx3.init()
engine.say("Hello, world!")
engine.runAndWait()
122. 物联网 - MQTT
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
client = mqtt.Client()
client.on_connect = on_connect
client.connect("mqtt.eclipse.org", 1883, 60)
client.loop_forever()
122. 计算机视觉 - scikit-image
from skimage import data, filters
import matplotlib.pyplot as plt
image = data.coins()
edges = filters.sobel(image)
plt.imshow(edges, cmap='gray')
plt.show()
123. 科学计算 - SciPy
from scipy import stats
print(stats.norm.cdf(0))
124. 模拟仿真 - SimPy
import simpy
def car(env):
while True:
print('Start parking at %d' % env.now)
yield env.timeout(5)
print('Start driving at %d' % env.now)
yield env.timeout(2)
env = simpy.Environment()
env.process(car(env))
env.run(until=15)
125. 图论 - NetworkX
import networkx as nx
G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4)])
print(list(nx.shortest_path(G, 1, 4)))
126. 数据清洗 - OpenRefine
# 安装OpenRefine
brew install --cask openrefine
# 启动OpenRefine
openrefine
127. 自动化任务 - Airflow
bash
# 安装Airflow
pip install apache-airflow
# 初始化数据库
airflow db init
# 启动Web服务器
airflow webserver --port 8080
# 启动调度器
airflow scheduler
128. 数据管道 - Luigi
import luigi
class MyTask(luigi.Task):
def run(self):
with self.output().open('w') as f:
f.write('Hello, world!')
def output(self):
return luigi.LocalTarget('output.txt')
if __name__ == '__main__':
luigi.run()
129. API 文档 - Swagger
from flask import Flask, jsonify
from flask_swagger_ui import get_swaggerui_blueprint
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({'data': 'value'})
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'
swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL, config={'app_name': "Test application"})
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
if __name__ == '__main__':
app.run()
- 数据流处理 - Apache Kafka
from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers='localhost:9092')
producer.send('my_topic', b'Hello, World!')
producer.close()
- 微服务架构 - gRPC
# 安装gRPC工具
pip install grpcio grpcio-tools
# 编译.proto文件
-m grpc_tools.protoc -I. --_out=. --grpc__out=. my_service.proto
- 云计算 - Boto3
import boto3
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
print(bucket.name)
- 区块链 - Web3.py
from web3 import Web3
web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))
print(web3.isConnected())
- 3D 渲染 - Pygame
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255))
pygame.display.flip()
pygame.quit()
- 量子计算 - Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer, execute
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = Aer.get_backend('qasm_simulator')
qobj = assemble(transpile(qc, backend))
result = execute(qc, backend).result()
print(result.get_counts())
- Web 框架 - Tornado
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([(r"/", MainHandler)])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
- 网络扫描 - Scapy
from scapy.all import sr1, IP, ICMP
packet = IP(dst="8.8.8.8")/ICMP()
response = sr1(packet)
print(response.show())
- 虚拟化 - Docker SDK
import docker
client = docker.from_env()
client.containers.run("ubuntu", "echo hello world")
- 网络拓扑 - Mininet
from mininet.net import Mininet
from mininet.node import Controller
net = Mininet(controller=Controller)
net.addController('c0')
h1 = net.addHost('h1')
h2 = net.addHost('h2')
s1 = net.addSwitch('s1')
net.addLink(h1, s1)
net.addLink(h2, s1)
net.start()
h1.cmd('ping -c1 %s' % h2.IP())
net.stop()
- 文本处理 - TextBlob
from textblob import TextBlob
blob = TextBlob("I love programming")
print(blob.sentiment)
- 图形界面 - PyQt5
from PyQt5.QtWidgets import QApplication, QLabel
app = QApplication([])
label = QLabel('Hello, World!')
label.show()
app.exec_()
- 视频处理 - moviepy
from moviepy.editor import VideoFileClip
clip = VideoFileClip("my_video.mp4")
clip = clip.subclip(0, 10)
clip.write_videofile("subclip.mp4")
- 游戏开发 - Pyglet
import pyglet
window = pyglet.window.Window()
@window.event
def on_draw():
window.clear()
pyglet.text.Label('Hello, world', font_name='Times New Roman', font_size=36, x=window.width//2, y=window.height//2, anchor_x='center', anchor_y='center').draw()
pyglet.app.run()
- AR/VR - Vizard
import viz
viz.go()
viz.addChild('piazza.osgb')
viz.MainView.setPosition([0,1.8,0])
- 爬虫工具 - Scrapy
import scrapy
class MySpider(scrapy.Spider):
name = "my_spider"
start_urls = ['http://example.com']
def parse(self, response):
self.log('Visited %s' % response.url)
- 语义网 - RDFLib
from rdflib import Graph
g = Graph()
g.parse("http://www.w3.org/People/Berners-Lee/card.rdf")
for subj, pred, obj in g:
print(subj, pred, obj)
- PDF生成 - ReportLab
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
c = canvas.Canvas("example.pdf", pagesize=letter)
c.drawString(100, 750, "Hello, World!")
c.save()
- HTTP库 - httpx
import httpx
response = httpx.get('https://api.example.com/data')
print(response.json())
- 安全性 - cryptography
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
encrypted = cipher.encrypt(b"Secret message")
decrypted = cipher.decrypt(encrypted)
print(decrypted)
- 文本生成 - GPT-3
import openai
openai.api_key = 'YOUR_API_KEY'
response = openai.Completion.create(
engine="davinci",
prompt="Once upon a time",
max_tokens=50
)
print(response.choices[0].text.strip())
这些是更多的Python知识点和示例代码,希望对你有所帮助!