Python常用包介绍

发布于:2024-04-27 ⋅ 阅读:(20) ⋅ 点赞:(0)

数据处理

1.numpy(数据处理和科学计算)
import numpy as np
np.set_printoptions(precision=2, suppress=True) # 设置打印选项,保留两位小数,禁止科学计数法

arr = np.arange(1, 6) # 使用arange函数创建数组
print(arr)

# 输出:
# [1 2 3 4 5]
2.pandas(数据处理和分析)
import pandas as pd

data = [
    {'name': 'John', 'age': 20},
    {'name': 'Bob', 'age': 35},
    {'name': 'Alice', 'age': 25}
]

df = pd.DataFrame(data)
print(df)

# 输出:
#     name  age
# 0   John   20
# 1    Bob   35
# 2  Alice   25
3.matplotlib(数据可视化)
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [4, 2, 7, 5, 9]
plt.plot(x, y)
plt.show()

运行效果如下:
在这里插入图片描述

机器学习和深度学习

4.scikit-learn(机器学习工具)
from sklearn.linear_model import LinearRegression

X = [[1, 4], [2, 5], [3, 6]]
y = [8, 10, 12]
model = LinearRegression().fit(X, y)
print(model.predict([[4, 7]]))

5.tensorflow(深度学习框架)
import tensorflow as tf

x = tf.constant([1, 2, 3, 4])
y = tf.constant([5, 6, 7, 8])
z = tf.add(x, y)
sess = tf.Session()
print(sess.run(z))

6.keras(深度学习框架)
from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(10, input_dim=5, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')

开发应用

7.requests(HTTP 库)
import requests

response = requests.get('https://www.baidu.com')
print(response.text)

8.flask(Web 框架)
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

9.scrapy(网络爬虫框架)
import scrapy

class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://quotes.toscrape.com']

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {'text': quote.css('span.text::text').get(),
                   'author': quote.css('span small::text').get()}

10.beautifulsoup(HTML 解析器)
from bs4 import BeautifulSoup

html = '<html><head><title>这是标题</title></head><body><p>这是一个段落。</p ></body></html>'
soup = BeautifulSoup(html, 'html.parser')
print(soup.title.text)

11.selenium(Web 自动化测试)
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
search_box = driver.find_element_by_name('wd')
search_box.send_keys('Python')
search_box.submit()

12.ctypes(调用 C 语言库)
import ctypes

lib = ctypes.cdll.LoadLibrary('libexample.so')
lib.add(1, 2)
13.wxPython(GUI 开发)
import wx

app = wx.App()
frame = wx.Frame(None, title='Hello, wxPython!')
frame.Show()
app.MainLoop()

14.pillow(图像处理)
from PIL import Image

im = Image.open('test.jpg')
im.show()
15.openpyxl(处理 Excel 文件)
import openpyxl

wb = openpyxl.load_workbook('example.xlsx')
sheet = wb['Sheet1']
cell = sheet['A1']
print(cell.value)

16.nltk(自然语言处理)
import nltk

sent = 'This is a sentence.'
tokens = nltk.word_tokenize(sent)
print(tokens)
17.jieba(中文分词)
import jieba

text = '我爱中文分词'
words = jieba.cut(text)
for word in words:
	print(word)

18.re(正则表达式)
import re

text = 'The quick brown fox jumps over the lazy dog.'
pattern = re.compile('fox')
print(pattern.findall(text))
19.datetime(日期时间处理)
import datetime

dt = datetime.datetime.now()
print(dt)

20.random(随机数生成)
import random
print(random.randint(1, 10))

21.sys(系统模块)
import sys

if sys.platform == 'win32':
    print('当前是Windows平台')
elif sys.platform == 'linux':
    print('当前是Linux平台')
elif sys.platform == 'darwin':
    print('当前是Mac平台')

# 输出:
# 当前是Windows平台