Python 常用库以及它们的简单代码示例:
1、NumPy:用于数值计算和数组操作。
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr)) # 计算数组均值
2、Pandas:用于数据分析和处理。
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
3、Matplotlib:用于绘制各种图表和可视化。
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.show()
4、Scikit-learn:用于机器学习和数据挖掘。
from sklearn import datasets
iris = datasets.load_iris()
X, y = iris.data, iris.target
5、TensorFlow:用于深度学习和神经网络。
import tensorflow as tf
x = tf.constant(5)
y = tf.constant(3)
z = x + y
with tf.Session() as sess:
print(sess.run(z))
6、Keras:基于 TensorFlow 或 Theano 的深度学习库。
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
7、OpenCV:用于计算机视觉和图像处理。
import cv2
image = cv2.imread('image.jpg')
cv2.imshow('image', image)
8、Beautiful Soup:用于解析 HTML 和 XML 数据。
from bs4 import BeautifulSoup
html = "<p>Python is awesome.</p>"
soup = BeautifulSoup(html, 'html.parser')
print(soup.get_text())
9、Requests:用于发送 HTTP 请求。
import requests
response = requests.get('https://api.github.com/user')
print(response.json)
10、NLTK:用于自然语言处理。
import nltk
text = "Hello, how are you?"
tokens = nltk.word_tokenize(text)
- Flask:用于构建 Web 应用程序。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
12、Django:用于构建 Web 应用程序和网站。
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello, World!")
- SQLAlchemy:用于操作关系型数据库。
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
14、Pygame:用于创建 2D 游戏。
import pygame
pygame.init()
- Tkinter:用于创建图形用户界面(GUI)。
import tkinter as tk
root = tk.Tk()