Python之所以成为全球最流行的编程语言之一,很大程度上得益于其丰富的标准库和强大的第三方库生态。本文将系统介绍Python常用库的功能特点和实际使用方法,帮助你快速提升Python编程技能。
标准库介绍
Python标准库是Python安装时自带的模块集合,涵盖了文件操作、网络通信、数据处理等各个领域。
1. os 模块
os模块提供了与操作系统交互的功能,包括文件和目录操作、环境变量管理等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import osprint (os.getcwd())os.makedirs('new_dir/sub_dir' , exist_ok=True ) for root, dirs, files in os.walk('.' ): for file in files: print (os.path.join(root, file)) print (os.environ.get('PATH' ))
2. sys 模块
sys模块提供了访问Python解释器运行时环境的功能。
1 2 3 4 5 6 7 8 9 import sysprint (sys.argv)print (sys.version)sys.exit(0 )
3. collections 模块
collections模块提供了高性能的数据结构。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from collections import Counter, defaultdict, dequecount = Counter(['a' , 'b' , 'a' , 'c' , 'b' , 'a' ]) print (count.most_common(2 ))d = defaultdict(list ) d['key' ].append(1 ) q = deque() q.append(1 ) q.appendleft(2 ) q.pop() q.popleft()
4. re 模块
re模块提供正则表达式功能。
1 2 3 4 5 6 7 8 9 10 11 import repattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' email = re.search(pattern, '联系我: test@example.com' ) print (email.group())text = re.sub(r'Python' , 'Java' , 'Python是最好的语言' ) result = re.split(r'[,;]' , 'a,b;c,d' )
5. json 模块
json模块用于处理JSON数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import jsondata = {'name' : '张三' , 'age' : 25 } json_str = json.dumps(data, ensure_ascii=False , indent=2 ) data = json.loads('{"name": "张三", "age": 25}' ) with open ('data.json' , 'w' , encoding='utf-8' ) as f: json.dump(data, f, ensure_ascii=False ) with open ('data.json' , 'r' , encoding='utf-8' ) as f: data = json.load(f)
数据处理库
1. NumPy
NumPy是Python科学计算的基础库,提供高性能的多维数组对象和数学函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import numpy as nparr = np.array([1 , 2 , 3 ]) matrix = np.array([[1 , 2 ], [3 , 4 ]]) print (arr.shape)print (arr.dtype)print (arr.reshape(3 , 1 ))result = arr + 2 dot_product = np.dot(matrix, matrix) print (np.mean(arr))print (np.std(arr))
2. Pandas
Pandas是数据处理和分析的利器,提供DataFrame数据结构。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import pandas as pddf = pd.DataFrame({ '姓名' : ['张三' , '李四' , '王五' ], '年龄' : [25 , 30 , 28 ], '城市' : ['北京' , '上海' , '广州' ] }) print (df.head())print (df.describe())result = df[df['年龄' ] > 25 ] df.to_csv('data.csv' , index=False , encoding='utf-8' ) df = pd.read_csv('data.csv' )
3. Matplotlib
Matplotlib是Python最常用的数据可视化库。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import matplotlib.pyplot as pltimport numpy as npplt.rcParams['font.sans-serif' ] = ['SimHei' ] x = np.linspace(0 , 10 , 100 ) y = np.sin(x) plt.plot(x, y, label='sin(x)' ) plt.xlabel('X轴' ) plt.ylabel('Y轴' ) plt.legend() plt.show()
Web开发库
1. requests
requests是最流行的HTTP请求库,简洁易用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import requestsresponse = requests.get('https://api.example.com/data' , params={'page' : 1 }) print (response.status_code)print (response.json())data = {'username' : 'test' , 'password' : '123456' } response = requests.post('https://api.example.com/login' , data=data) headers = {'User-Agent' : 'Mozilla/5.0' } response = requests.get('https://example.com' , headers=headers) response = requests.get('https://example.com/image.jpg' , stream=True ) with open ('image.jpg' , 'wb' ) as f: f.write(response.content)
2. Flask
Flask是轻量级的Web框架,适合快速构建Web应用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from flask import Flask, jsonify, requestapp = Flask(__name__) @app.route('/' ) def index (): return 'Hello, Flask!' @app.route('/api/data' ) def get_data (): return jsonify({'message' : 'success' , 'data' : []}) @app.route('/api/submit' , methods=['POST' ]) def submit (): data = request.get_json() return jsonify({'received' : data}) if __name__ == '__main__' : app.run(debug=True )
爬虫库
1. BeautifulSoup
BeautifulSoup是HTML解析库,用于从网页中提取数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 from bs4 import BeautifulSoupimport requestsresponse = requests.get('https://example.com' ) soup = BeautifulSoup(response.text, 'html.parser' ) print (soup.title.string)for link in soup.find_all('a' ): print (link.get('href' ))
机器学习库
1. Scikit-learn
Scikit-learn是Python最流行的机器学习库,提供各种经典算法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorimport numpy as npX = np.random.rand(100 , 2 ) y = X[:, 0 ] * 2 + X[:, 1 ] * 3 + 1 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 ) model = LinearRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) print (f'MSE: {mean_squared_error(y_test, y_pred):.2f}' )
实用工具库
1. Pillow
Pillow是Python图像处理库。
1 2 3 4 5 6 7 8 9 10 11 12 from PIL import Imageimg = Image.open('test.jpg' ) img = img.resize((200 , 200 )) gray_img = img.convert('L' ) gray_img.save('gray.jpg' )
总结
Python的库生态非常丰富,从标准库到第三方库,几乎覆盖了所有编程领域。掌握常用库的使用是提升Python编程效率的关键。本文介绍的库只是冰山一角,还有更多优秀的库等待你去探索和学习。