📜  Python的10个有趣模块(1)

📅  最后修改于: 2023-12-03 14:46:45.517000             🧑  作者: Mango

Python的10个有趣模块

Python是一种高级编程语言,具有易学易用、功能强大等优点,在数据科学、Web开发、游戏开发、机器学习等做得很好。除了其内置功能以外,Python还有很多有趣的模块。下面介绍了10个非常常用、且相当有趣的Python模块。

1. NumPy

NumPy是Python中最常用的科学计算库。它提供了一种强大的数据结构,称为数组。可以使用数组高效地进行数学运算。NumPy还包括了许多工具和函数,可以快速处理和分析大规模数据。它是人工智能和机器学习中使用最广泛的Python模块。

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + b

print(c)

输出:

[5 7 9]
2. Pandas

Pandas是Python中最常用的数据处理模块。它提供了一种数据结构,称为DataFrame,用于处理表格型数据。 Pandas还提供了很多数据操作方法,可以用于数据清洗、数据筛选、数据转换、多表合并等。

import pandas as pd

data = {'name': ['John', 'Amy', 'Bob', 'Sally'],
        'age': [30, 25, 40, 18],
        'country': ['USA', 'UK', 'Canada', 'France']}
df = pd.DataFrame(data)

print(df.head())

输出:

   name  age country
0  John   30     USA
1   Amy   25      UK
2   Bob   40  Canada
3 Sally   18  France
3. Matplotlib

Matplotlib是Python中最常用的数据可视化库。它可以创建出柱形图、线条图、散点图、饼图等多种类型的图表。Matplotlib可以设置图表的样式、标签、标题等,使图表更加美观易读。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine Wave')
plt.show()

Sine Wave

4. Seaborn

Seaborn是Python中的另一个数据可视化库,是建立在Matplotlib之上的。Seaborn提供了多种内置可视化模板,可以快速创建出各类图表,例如分类散点图、热力图、密度图等。与Matplotlib不同的是,Seaborn提供了一些默认的样式和配色方案,使得图表更加漂亮。

import seaborn as sns
import pandas as pd

data = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
sns.swarmplot(x="species", y="petal_length", data=data)

Swarm Plot

5. Pygame

Pygame是一个Python模块,用于开发电子游戏。它提供了2D游戏引擎、碰撞检测、音频、事件循环等功能,可以让开发者轻松地制作出各类游戏,包括沙盒游戏、飞行射击游戏等。

import pygame, sys
from pygame.locals import *

pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()

WINDOW = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Pygame Demo')

BLUE = (0, 0, 255)
x, y = 30, 30
direction = 'right'

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    WINDOW.fill((255, 255, 255))

    if direction == 'right':
        x += 5
        if x == 280:
            direction = 'down'
    elif direction == 'down':
        y += 5
        if y == 220:
            direction = 'left'
    elif direction == 'left':
        x -= 5
        if x == 30:
            direction = 'up'
    elif direction == 'up':
        y -= 5
        if y == 30:
            direction = 'right'

    pygame.draw.rect(WINDOW, BLUE, (x, y, 40, 40))

    pygame.display.update()
    fpsClock.tick(FPS)

Pygame Demo

6. Gensim

Gensim是一个自然语言处理的Python库。它可以用于实现文本挖掘、信息抽取、主题建模等功能。Gensim支持多种提取语义组件的算法,例如LSA、LSI、TF-IDF、Word2Vec等。

from gensim.models import Word2Vec
sentences = [['this', 'is', 'a', 'sentence'], ['this', 'is', 'another', 'sentence']]
model = Word2Vec(sentences, min_count=1, size=300)
print(model)

输出:

Word2Vec(vocab=7, size=300, alpha=0.025)
7. NLTK

Natural Language Toolkit (NLTK) 是一个Python模块,用于人类自然语言处理和机器学习。它包括语料库、词汇数据集等,包括一些用于词干提取、词性标注、分块、句法分析等的工具。

import nltk
nltk.download('punkt')
text = '''In computing, time-sharing is the sharing of a computing resource among many users by means of multiprogramming and multi-tasking at the same time.[1] Its introduction in the 1960s and emergence as the prominent model of computing in the 1970s represented a major technological shift in the history of computing. 
'''
words = nltk.word_tokenize(text)
print(words)

输出:

['In', 'computing', ',', 'time-sharing', 'is', 'the', 'sharing', 'of', 'a', 'computing', 'resource', 'among', 'many', 'users', 'by', 'means', 'of', 'multiprogramming', 'and', 'multi-tasking', 'at', 'the', 'same', 'time', '.', '[', '1', ']', 'Its', 'introduction', 'in', 'the', '1960s', 'and', 'emergence', 'as', 'the', 'prominent', 'model', 'of', 'computing', 'in', 'the', '1970s', 'represented', 'a', 'major', 'technological', 'shift', 'in', 'the', 'history', 'of', 'computing', '.']
8. OpenCV

OpenCV是一个开源计算机视觉的Python库,广泛应用于图像和视频处理。它含有超过2500个优化过的算法,涵盖图像处理、计算机视觉、机器学习等领域。OpenCV同样也支持多种语言的调用,包括C++、Java等。

import cv2
img = cv2.imread('lena.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', gray)
cv2.waitKey()
cv2.destroyAllWindows()

Gray Image

9. Turtle

Turtle是一个绘制图形的Python库,适用于绘制简单的图像和游戏开发学习。Turtle包含了基本的绘图命令,可以用于绘制图形,如线条、多边形、圆形等等。

import turtle
t = turtle.Turtle()
t.color('red')
t.speed(1)

for i in range(4):
    t.forward(100)
    t.right(90)

turtle.done()

Square

10. Requests

Requests是一个Python库,用于发送HTTP/1.1请求。它支持多种HTTP方法,包括GET、POST等,还可以自定义请求头、参数、数据,帮助开发者制作 Web API。

import requests

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

输出:

200
<!DOCTYPE html>
<!--STATUS OK-->