Object Oriented Python 简明教程

Object Oriented Python - Libraries

Requests − Python Requests Module

Requests是Python的一个模块,它是一个优雅而简单的Python HTTP库。有了它,你可以发送各种HTTP请求。通过这个库,我们可以添加头信息、表单数据、多部分文件和参数,以及访问响应数据。

Requests is a Python module which is an elegant and simple HTTP library for Python. With this you can send all kinds of HTTP requests. With this library we can add headers, form data, multipart files and parameters and access the response data.

由于Requests不是一个内置模块,因此我们首先需要安装它。

As Requests is not a built-in module, so we need to install it first.

你可以通过在终端中运行以下命令来安装它:

You can install it by running the following command in the terminal −

pip install requests

安装模块后,你可以通过在Python shell中键入以下命令来验证安装是否成功。

Once you have installed the module, you can verify if the installation is successful by typing below command in the Python shell.

import requests

如果安装成功,你将不会看到任何错误消息。

If the installation has been successful, you won’t see any error message.

Making a GET Request

作为示例,我们将使用“pokeapi”

As a means of example we’ll be using the “pokeapi”

pokeapi

Output −

pokeapi output

Making POST Requests

requests 库方法适用于所有当前使用的 HTTP 动词。如果您想对 API 终结点发出一个简单的 POST 请求,则可以这样做 −

The requests library methods for all of the HTTP verbs currently in use. If you wanted to make a simple POST request to an API endpoint then you can do that like so −

req = requests.post(‘http://api/user’, data = None, json = None)

与我们之前的 GET 请求相同,但这具有两个额外的关键字参数 −

This would work in exactly the same fashion as our previous GET request, however it features two additional keyword parameters −

  1. data which can be populated with say a dictionary, a file or bytes that will be passed in the HTTP body of our POST request.

  2. json which can be populated with a json object that will be passed in the body of our HTTP request also.

Pandas: Python Library Pandas

Pandas 是一个开源 Python 库,提供高性能的数据操作和分析工具,并使用其强大的数据结构。Pandas 是数据科学中最广泛使用的 Python 库之一。它主要用于数据整理,原因有很多:功能强大且灵活。

Pandas is an open-source Python Library providing high-performance data manipulation and analysis tool using its powerful data structures. Pandas is one of the most widely used Python libraries in data science. It is mainly used for data munging, and with good reason: Powerful and flexible group of functionality.

基于 Numpy 包,关键数据结构称为 DataFrame。这些数据框架使我们能够存储和操作表格数据,其中包括观测行和变量列。

Built on Numpy package and the key data structure is called the DataFrame. These dataframes allows us to store and manipulate tabular data in rows of observations and columns of variables.

有几种创建 DataFrame 的方法。一种方法是使用词典。例如 −

There are several ways to create a DataFrame. One way is to use a dictionary. For example −

dataframe

Output

dataframe output

从输出中,我们可以看到新的 brics DataFrame,Pandas 已为每个国家分配了一个键,从数值 0 到 4。

From the output we can see new brics DataFrame, Pandas has assigned a key for each country as the numerical values 0 through 4.

如果不给出 0 到 4 的索引值,而希望有不同的索引值(例如,两个字母的国家代码),也可以轻松地做到 −

If instead of giving indexing values from 0 to 4, we would like to have different index values, say the two letter country code, you can do that easily as well −

将下面的代码添加到上面的代码中,得到

Adding below one lines in the above code, gives

brics.index = ['BR', 'RU', 'IN', 'CH', 'SA']

Output

dataframe brics index

Indexing DataFrames

indexing dataframes

Output

indexing dataframes output

Pygame

Pygame 是一个开源且跨平台的库,用于制作包括游戏在内的多媒体应用程序。它包含计算机图形和声音库,旨在与 Python 编程语言配合使用。您可以使用 Pygame 开发很多酷炫的游戏。

Pygame is the open source and cross-platform library that is for making multimedia applications including games. It includes computer graphics and sound libraries designed to be used with the Python programming language. You can develop many cool games with Pygame.’

Overview

Pygame 由多个模块组成,每个模块处理一组特定任务。例如,display 模块处理显示窗口和屏幕,draw 模块提供绘制形状的函数,key 模块处理键盘。这些只是库中的几个模块。

Pygame is composed of various modules, each dealing with a specific set of tasks. For example, the display module deals with the display window and screen, the draw module provides functions to draw shapes and the key module works with the keyboard. These are just some of the modules of the library.

Pygame 库的主页位于 https://www.pygame.org/news

The home of the Pygame library is at https://www.pygame.org/news

要制作 Pygame 应用程序,请按照以下步骤:

To make a Pygame application, you follow these steps −

导入 Pygame 库

Import the Pygame library

import pygame

初始化 Pygame 库

Initialize the Pygame library

pygame.init()

创建一个窗口。

Create a window.

screen = Pygame.display.set_mode((560,480))
Pygame.display.set_caption(‘First Pygame Game’)

Initialize game objects

Initialize game objects

在这一步,我们会加载图片,加载声音,进行对象定位,设置一些状态变量等。

In this step we load images, load sounds, do object positioning, set up some state variables, etc.

Start the game loop.

Start the game loop.

它只是一个循环,处理事件,检查输入,移动对象并绘制它们。循环的每次迭代称为一次帧。

It is just a loop where we continuously handle events, checks for input, move objects, and draw them. Each iteration of the loop is called a frame.

将以上所有逻辑及入到下方程序中,

Let’s put all the above logic into one below program,

Pygame_script.py

Pygame_script.py

pygame script

Output

pygame script output

Beautiful Soup: Web Scraping with Beautiful Soup

网络抓取背后的总想法是获取存在于网站上的数据,并将其转换为可用于分析的格式。

The general idea behind web scraping is to get the data that exists on a website, and convert it into some format that is usable for analysis.

它是一个用于从 HTML 或 XML 文件中提取数据的 Python 库。凭借您最喜欢的解析器,它提供了解析、搜索和修改解析树的惯用方法。

It’s a Python library for pulling data out of HTML or XML files. With your favourite parser it provide idiomatic ways of navigating, searching and modifying the parse tree.

由于 BeautifulSoup 不是内置库,因此我们需要在尝试使用它之前将其安装。若要安装 BeautifulSoup,请运行以下命令:

As BeautifulSoup is not a built-in library, we need to install it before we try to use it. To install BeautifulSoup, run the below command

$ apt-get install Python-bs4 # For Linux and Python2
$ apt-get install Python3-bs4 # for Linux based system and Python3.

$ easy_install beautifulsoup4 # For windows machine,
Or
$ pip instal beatifulsoup4 # For window machine

安装完成后,我们就可以运行一些示例并详细探索 Beautifulsoup,

Once the installation is done, we are ready to run few examples and explores Beautifulsoup in details,

beautifulsoup in details

Output

beautifulsoup in details output

以下是一些导航该数据结构的简单方法 −

Below are some simple ways to navigate that data structure −

data structure

一项常见任务是从页面 <a> 标签中提取所有 URL −

One common task is extracting all the URLs found within a page’s <a> tags −

urls

另一项常见任务是从页面中提取所有文本 −

Another common task is extracting all the text from a page −

text from page