AskPython-博客中文翻译-四-

AskPython 博客中文翻译(四)

原文:AskPython Blog

协议:CC BY-NC-SA 4.0

Flask REST API–为您的 Flask 应用程序设置指南

原文:https://www.askpython.com/python-modules/flask/flask-rest-api

在本文中,我们将熟悉 API 和 REST API,然后构建我们自己的 Flask REST API 应用程序。

什么是 API?

API 或应用程序编程接口提供了与不同应用程序交互的接口。使用 API,我们可以检索、处理、发送来自其他应用程序的数据****–值

例如,考虑一个 Web 应用程序。客户端发送一些数据作为请求,服务器处理这些数据,然后将适当的响应数据发送回客户端。

整个交互过程都是通过 API 完成的。所以让我们再看一下这个例子,看看 API 的作用在哪里。

因此,客户端发送给服务器的是一个包含请求数据的 API。服务器对其进行处理,然后将包含相应响应数据的另一个 API 发送回客户端。

CRUD 操作符和 HTTP 方法

在使用 API 时,客户端可以通过多种方式向服务器发送请求数据。这些类型被称为 CRUD 操作。

每个 CRUD(Create Retrieve Update Delete)操作符都有一个与之关联的 HTTP 方法。

现在让我们来看看它们:

  • GET HTTP Method—从服务器检索特定信息(用于查看目的)。
  • POST—在服务器数据库中发送/创建新信息。
  • PUT–编辑/更新数据库中的信息,或者在数据库中没有信息时添加信息。
  • 删除—从服务器数据库中删除信息。

好了,现在我们知道了这些方法,让我们了解一下什么时候使用它们。考虑下面的例子:

我们有一个学生数据库,包含像姓名、班级、年龄等信息。

  • 查看学生列表——使用获取 HTTP 的方法
  • 添加一个新的学生信息——使用 POST HTTP 方法
  • 编辑某个学生的某些信息(班级/年龄)——使用 PUT HTTP 方法
  • 要从数据库中删除学生的信息,请使用 DELETE HTTP 方法

什么是 REST API?

REST ( 具象状态转移 ) API 类似于标准 API。这里,当我们向服务器发送请求时,不像 API 用数据响应,REST API 用资源响应。

REST API 资源

什么是资源??

资源是数据,但我们看待它的方式会改变。参考资料类似于面向对象编程。下面举个例子让我们理解一下:

考虑一个烧瓶视图—“/Book/Book 123”

在这里,同一个视图端点可以执行 4 个操作。

  • 获取 Book/Book123: 显示关于 Book123 的信息。
  • POST Book/Book123 :创建一本新书“Book123”
  • PUT Book/Book123 :更新/编辑图书“Book123”的信息
  • 删除图书/图书 123: 从数据库中删除“图书 123”

由于一个实体有几种功能(OOP 方法),它可以被认为是一个图书资源。

因此,现在客户机和服务器之间的交互不是针对单个端点请求,而是针对资源(针对不同操作的同一个端点)

REST APIs 的无状态性

REST API 的另一个特性是它的无状态性。这意味着在服务器完成一个动作后,它会忘记它。

我们用一个例子来理解这个。

考虑一下我们上面看到的图书资源。比方说,我使用 POST 方法发送一本书的数据 Stephen Hawkings 的《时间简史》。

服务器会将该信息添加到数据库中,然后忘记该操作。那就是下一次我使用一个 GET 请求来检索这本书;服务器将不会有先前 POST 方法操作的任何记忆。

服务器将首先进入数据库并搜索这本书。一旦它找到了这本书,它就会用这些数据来回应。再一次在它完成动作后,它会忘记这件事。

JSON 在客户机-服务器 API 交互中的应用

API 使用 JSON 格式用于接受返回请求

也就是说,客户机将请求数据作为 JSON 文本发送给服务器。类似地,服务器处理数据并将响应作为 JSON 文本再次返回。

因此,一个基于 REST API 的 Web 应用的整个流程如下:

  • 用户将请求数据作为 JSON 发送给服务器。
  • 服务器首先将 JSON 转换成 python 可读的格式。
  • 然后,服务器处理请求并再次创建响应数据作为 JSON
  • 然后网页模板将 JSON 响应转换成用户可读的格式,并在网页上显示出来。

因此,API 中客户端(前端)和服务器(后端)之间真正的信息交换是使用 JSON 文本进行的。

JSON 格式类似于 Python 字典:

{
    'student1':{
        'name':'XYZ',
        'age' : 21
    }
}

安装邮递员

Postman 是一个 API 开发的协作平台。Postman 的特性简化了构建 API 的每个步骤,并简化了协作,因此您可以更快地创建更好的 API。

点击这里下载邮差。安装完成后,它将如下所示:

POSTMAN Window

POSTMAN Window

好了,编码员们!阅读完了,现在让我们开始构建我们的 REST API。

构建 Flask REST API 应用程序

在这一节中,我们将使用 Flask RESTFul 库构建一个简单的 Book REST API 应用程序。所以让我们开始吧!!

1.将 Flask_restful 安装到系统中

要安装 Flask _ RestFull 包,运行 pip 命令:

pip install flask_restful

现在已经安装好了,让我们继续数据库部分

2.使用 SQLAlchemy 对数据库模型进行编码

这里我们将使用 SQLite 数据库来存储我们的模型。要使用它们,首先安装 flask_sqlalchemy

pip install flask_sqlalchemy

现在创建一个 models.py 文件,并添加以下代码

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class BookModel(db.Model):
    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    price = db.Column(db.Integer())
    author = db.Column(db.String(80))

    def __init__(self, name, price, author):
        self.name = name
        self.price = price
        self.author = author 

    def json(self):
        return {"name":self.name, "price":self.price, "author":self.author}

这里,BookModel 有一个名称、价格和作者字段。由于 API 在 JSON 中,我们创建了一个对象方法。json() 返回一个 JSON book 对象。

我们首先必须实例化一个 DB 实例来创建 DB 模型。如果您对 SQLAlchemy 有任何疑问,请查看我们的 SQLAlchemy 教程

既然我们已经有了模型,现在让我们编写主要的 Flask 应用程序。

3.编写烧瓶应用程序

对于 Flask REST API,我们需要包含一个额外的 API(app) 实例来指示 Flask 这是一个 REST API web app。

from flask import Flask
from flask_restful import Api

app = Flask(__name__)

api = Api(app) #Flask REST Api code 

if __name__ == '__main__':
    app.run(host='localhost', port=5000)

接下来,我们需要向 SQLAlchemy 提供 SQLite 信息,并将 DB 实例(form models.py)与这个应用程序文件链接起来。

为此,添加代码:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

在这里,将 < db_name > 替换为您想要的 db 名称。

为了简单起见,SQLALCHEMY_TRACK_MODIFICATIONS 保持 False

第三行将 DB 实例与应用程序链接起来。我们需要 DB 文件,以便网页用户可以使用它。此外,我们要求在第一个用户请求之前。

因此,为了创建该文件,我们使用函数:

@app.before_first_request
def create_table():
    db.create_all()

将它添加到上面给出的代码本身的下面。好了,现在让我们编写 Flask REST API 资源类。

4.添加图书列表资源

该资源将完成以下任务:

  • GET 方法:显示数据库中的图书列表
  • 发布方法:将新书信息添加到数据库中

所以代码看起来会像这样:

class BooksList(Resource):
    def get(self):
        #get all objects from BookModel
        #return the JSON text of all objects
        pass

    def post(self):
        #convert the JSON data sent by the user to python-format
        #create a new bookModel object and send in the data
        #save to DB
        pass

所以代码应该能够完成上面写的任务。现在让我们用实际代码替换注释:

class BooksList(Resource):
    def get(self):
        books = BookModel.query.all()
        return {'Books':list(x.json() for x in books)}

    def post(self):
        data = request.get_json()
        new_book = BookModel(data['name'],data['price'],data['author'])
        db.session.add(new_book)
        db.session.commit()
        return new_book.json(),201

在 GET 方法中,

  • 使用 BookModle.query.all() 获取数据库中的图书
  • 将书的 JSON 文本一个一个显示为列表

在 POST 方法中,

  • 使用 request.get_json() 转换 JSON 数据
  • 创建新书信息并将其添加到数据库中

就是这样;最后,我们需要提到 BooksList 资源的 URL 端点

api.add_resource(BooksView, '/books')

5.添加图书资源

现在,我们将创建一个资源,它将:

  • GET 方法:只显示用户请求的特定书籍
  • PUT 方法:编辑特定图书的信息。如果没有,请创建一个
  • 删除方法:删除特定的书

这里的代码看起来像这样:

class Book(Resource):
    def get(self,name):
        #get the book with the name given by the user
        #if book exists, return it else return 404 not found 

    def put(self,name):
        #convert the JSON data sent by the user to python-format
        #Search if the book exists
        #if it exists, update it with the data given by the user 
        #if does not exists, create and add the book into DB

    def delete(self,name):
        #Search if the book exists in the DB
        #delete it

代码应该能够完成上述所有任务。所以添加代码:

class Book(Resource):
    def get(self,name):
        book = BookModel.query.filter_by(name=name).first()
        if book:
            return book.json()
        return {'message':'book not found'},404

    def put(self,name):
        data = request.get_json()

        book = BookModel.query.filter_by(name=name).first()

        if book:
            book.price = data["price"]
            book.author = data["author"]
        else:
            book = BookModel(name=name,**data)

        db.session.add(book)
        db.session.commit()

        return book.json()

    def delete(self,name):
        book = BookModel.query.filter_by(name=name).first()
        if book:
            db.session.delete(book)
            db.session.commit()
            return {'message':'Deleted'}
        else:
            return {'message': 'book not found'},404

在 GET 方法中,

  • book model . query . filter _ by(name = name)。first() 返回它从数据库中获得的第一本书。如果找不到任何具有该名称的内容,则返回 None。
  • 如果找到,返回书的 JSON 文本。否则返回 404

在 PUT 方法中,

  • 使用 request.get_json() 转换 JSON 数据
  • 搜索书名为的书。
  • 如果存在,用新发送的数据替换旧数据
  • 或者创建一个新的图书对象
  • 将其添加到数据库中

在删除方法中,

  • 获取用户给定名称的书籍
  • 删除它

就是这样。最后,为这个资源添加 URL 端点

api.add_resource(BookView,'/book/<string:name>')

我们完了。!

Flask Rest API 应用程序的最终代码

因此,下面给出了组合烧瓶的主要应用:

from flask import Flask,request
from flask_restful import Api, Resource, reqparse
from models import db, BookModel

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

api = Api(app)
db.init_app(app)

@app.before_first_request
def create_table():
    db.create_all()

class BooksView(Resource):
    '''
    parser = reqparse.RequestParser()
    parser.add_argument('name',
        type=str,
        required=True,
        help = "Can't leave blank"
    )
    parser.add_argument('price',
        type=float,
        required=True,
        help = "Can't leave blank"
    )
    parser.add_argument('author',
        type=str,
        required=True,
        help = "Can't leave blank"
    )'''

    def get(self):
        books = BookModel.query.all()
        return {'Books':list(x.json() for x in books)}

    def post(self):
        data = request.get_json()
        #data = BooksView.parser.parse_args()

        new_book = BookModel(data['name'],data['price'],data['author'])
        db.session.add(new_book)
        db.session.commit()
        return new_book.json(),201

class BookView(Resource):
    '''
    parser = reqparse.RequestParser()
    parser.add_argument('price',
        type=float,
        required=True,
        help = "Can't leave blank"
        )
    parser.add_argument('author',
        type=str,
        required=True,
        help = "Can't leave blank"
        )'''

    def get(self,name):
        book = BookModel.query.filter_by(name=name).first()
        if book:
            return book.json()
        return {'message':'book not found'},404

    def put(self,name):
        data = request.get_json()
        #data = BookView.parser.parse_args()

        book = BookModel.query.filter_by(name=name).first()

        if book:
            book.price = data["price"]
            book.author = data["author"]
        else:
            book = BookModel(name=name,**data)

        db.session.add(book)
        db.session.commit()

        return book.json()

    def delete(self,name):
        book = BookModel.query.filter_by(name=name).first()
        if book:
            db.session.delete(book)
            db.session.commit()
            return {'message':'Deleted'}
        else:
            return {'message': 'book not found'},404

api.add_resource(BooksView, '/books')
api.add_resource(BookView,'/book/<string:name>')

app.debug = True
if __name__ == '__main__':
    app.run(host='localhost', port=5000)

models.py 文件:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class BookModel(db.Model):
    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    price = db.Column(db.Integer())
    author = db.Column(db.String(80))

    def __init__(self, name, price, author):
        self.name = name
        self.price = price
        self.author = author 

    def json(self):
        return {"name":self.name, "price":self.price, "author":self.author}

现在让我们运行我们的服务器,并使用 POSTMAN 检查它们。

使用 POSTMAN 实现 Flask REST API 应用程序

运行服务器并转到 POSTMAN。

1.图书列表资源:发布方法

使用 POST 方法转到“ /books ”端点

在正文中,选择raw–JSON并在正文中添加 JSON 数据

{
	"name":"book1",
	"price":123,
	"author":"author1"
}

点击发送

POST

POST

图书-图书 1 被创建

2.图书列表资源:发布方法

使用 GET 方法转到“ books/ ”并点击 send。您将获得数据库中的图书列表

GET

GET

因为我们只有 book1 ,所以它在列表中只显示 1 个对象。

3.图书资源:获取方法

现在使用 GET 进入“/books/ book1 ”并点击 send

GET

GET

看,它显示了第一本书的信息

4.图书资源:PUT 方法

使用 PUT 方法转到“/books/ book1 ”,并在正文中添加以下 JSON。

{
	"price": 100,
	"author":"author123"
}

由于名称已经通过 URL 请求发送,我们需要发送价格和作者 JSON。

点击发送

PUT

PUT

价格和作者价值观都变了!!也尝试使用 GET 方法来检查它们。

5.书籍资源:删除方法

使用删除方法转到“/books/ book1

DELETE

DELETE

看到就删!

结论

就这样伙计们!希望你对 Flask REST API 框架有了足够的了解。为了更好地理解,请亲自尝试以上代码。

下次见!!

Flask Route–如何在 Flask 中执行 URL 路由?

原文:https://www.askpython.com/python-modules/flask/flask-route

本文将处理 Flask route 以在 Flask 中执行 URL 路由,然后在我们的 flask 应用程序中实现它。所以让我们开始吧!!

什么是 URL 路由?

URL 路由用于将特定功能(带有网页内容)链接到其网页 URL。

当我们点击一个端点时,网页将显示其内容,这是使用路由链接到 URL 端点的函数的输出。

我们可以通过以下方式进行 URL 路由:

如何将 URL 路由到函数

让我们学习设置烧瓶路线的不同方法。

1。使用 app.route()

这里使用的语法如下:

@app.route('<endpoint>')

因此,URL 为–“localhost:5000/page”的 Flask 应用程序网页示例如下所示:

from flask import Flask

app = Flask(__name__)

@app.route('/blogs')
def blogs():
    return 'Welcome to Blog site'

app.run(host='localhost', port=5000)

注意:函数名应该与端点名相同。

运行应用程序:

python filename.py

Blogs

Blogs

我们也可以有一个带有可变端点的 URL。此类 URL 用于其功能接受来自用户的参数的网页。

考虑功能:

from flask import Flask

app = Flask(__name__)

@app.route('/blogs/<int:id>')
def blogs(id):
    return f"Welcome to Blog number:{id}"

app.run(host='localhost', port=5000)

注意:这里非变量端点(博客)将是函数名,端点变量( id )将是函数的参数。

现在,你可能已经猜到了,基于可变端点,网页将显示不同的输出。

Blog id

Blog id

2。使用 add_url_route() 属性

当我们需要在不使用 decorators 的情况下在外部路由一个函数时,通常使用这个函数。语法:

app.add_url_route('<url_rule(endpoint_structure)>','<endpoint_name>',<view_function>')

因此,请考虑下面的文件:

from flask import Flask

app = Flask(__name__)

def blogs():
    return f"Welcome to Blog Site"

app.add_url_rule('/blogs','blogs', blogs)

app.run(host='localhost', port=5000)

这里的输出将和以前一样。

Blogs

Blogs

类似地,变量 endpoint 的语法是:

app.add_url_rule('<url_rule_with_variable>','<endpoint_name>',<view_function>)

变量端点文件语法如下:

from flask import Flask

app = Flask(__name__)

def blogs(id):
    return f"Welcome to Blog number:{id}"

app.add_url_rule('/blogs/<int:id>','blogs',blogs)

app.run(host='localhost', port=5000)

运行应用程序并注意输出:

Blog 1

Blog 1

这里的输出也和以前一样。

结论

本教程到此为止,各位!为了更好地理解,请亲自尝试上面给出的例子。

下一篇文章再见!到那时,快乐的编码!!

Flask Sessions–在 Flask 中设置用户会话

原文:https://www.askpython.com/python-modules/flask/flask-sessions

在本教程中,我们将处理 Flask 会话,并在 Flask Web 应用程序中使用它们。所以让我们开始吧。

Flask 中的会话是什么?

会话的功能类似于 Flask cookies ,除了它们存储在服务器上。

会话基本上是用户登录到服务器的持续时间。在整个会话期间跟踪的数据存储在服务器中。

每个会话都有一个会话 ID (用秘密密钥加密)。会话使用唯一的 id 来检索存储的值。每当创建会话时,包含唯一会话 id 的 cookie 就会存储在用户的计算机上。并随每个对服务器的请求一起返回。

当用户再次访问该站点时,他返回包含会话 ID 的 Cookie。然后,服务器读取会话 ID 并检索相应的会话数据。

为什么使用会话?

在客户端保存数据(以 cookie 的形式)通常不是一个好主意。其他一些威胁包括:

  1. 黑客可以发送一个假的 cookie,并以另一个用户的身份登录来攻击网站。
  2. 存储敏感数据,如用户密码等。在 cookies 中是不安全的。
  3. 我们只能在 cookies 中存储有限的数据,因为大多数浏览器不允许超过 4kb 的数据。

因此,为了解决这个问题,我们将所有关键用户信息on保存在服务器本身,并将会话 ID/密钥存储在客户端的计算机上(作为 Cookie)

动手操作设置烧瓶课程

好了,现在让我们深入到编码部分。在 Flask 中,一个名为会话对象字典对象用于跟踪会话数据。

语法非常简单:

session['<title>'] = value

这就是你设置会话的方式。现在要删除会话信息,我们使用session . pop()</strong>函数</p> <pre><code class="language-py">session.pop('<title>', None) </code></pre> <p>让我们考虑一个例子:</p> <pre><code class="language-py">@app.route('/setsession') def setsession(): session['Username'] = 'Admin' return f"The session has been Set" @app.route('/getsession') def getsession(): if 'Username' in session: Username = session['Username'] return f"Welcome {Username}" else: return "Welcome Anonymous" @app.route('/popsession') def popsession(): session.pop('Username',None) return "Session Deleted" </code></pre> <p>这里,</p> <ul> <li><strong>setsession()</strong> 视图将会话用户名设置为</li> <li>如果设置了用户名会话,那么 <strong>getsession()</strong> 视图将显示<strong>欢迎管理员</strong>,否则将简单地返回<strong>欢迎匿名</strong></li> <li>最后, <strong>popsession()</strong> 视图将从服务器中删除用户名会话。</li> </ul> <p>因此,最终代码将是:</p> <pre><code class="language-py">fom flask import Flask, session app = Flask(__name__) app.secret_key = "xyz" @app.route('/setsession') def setsession(): session['Username'] = 'Admin' return f"The session has been Set" @app.route('/getsession') def getsession(): if 'Username' in session: Username = session['Username'] return f"Welcome {Username}" else: return "Welcome Anonymous" @app.route('/popsession') def popsession(): session.pop('Username',None) return "Session Deleted" app.run(host='localhost', port=5000) </code></pre> <p>必须提到 <strong>secret_key</strong> ,因为会话使用秘密密钥进行加密。</p> <h2 id="代码的实现">代码的<strong>实现</strong></h2> <p>就是这样!现在让我们运行服务器并转到" <strong>/setsession</strong> "</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/467c6eeb03b22e1b60a1bf6f3ffc5343.png" alt="Set Session" loading="lazy"></p> <p>Set Session</p> <p>现在,当我们转到“<strong>/get session</strong>”URL 时,我们必须看到 Welcome Admin。所以让我们试试</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/16902d427d1edb6425bb2d4b29839dc9.png" alt="Get Session" loading="lazy"></p> <p>Get Session</p> <p>很好,现在我们将弹出/销毁会话,然后重新访问 <strong>getsession</strong> URL</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/dfc05b3f111118d4874c29acc96f15ae.png" alt="Pop Session" loading="lazy"></p> <p>Pop Session</p> <p>现在转到" <strong>/getsession</strong> "</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a7e990416778f9b07b3b640af4a011e4.png" alt="Get Session Anonymous" loading="lazy"></p> <p>Get Session Anonymous</p> <p>完美!</p> <h2 id="就这样"><strong>就这样!</strong></h2> <p>这都是关于烧瓶会议。我们希望你已经学会了设置你的第一次烧瓶会议所需要知道的一切。如果你有任何问题,请在评论中告诉我们。编码快乐!</p> <h1 id="flask-静态文件-python-flask-中静态文件的实现">Flask 静态文件 Python Flask 中静态文件的实现</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/flask/flask-static-files" target="_blank">https://www.askpython.com/python-modules/flask/flask-static-files</a></p> </blockquote> <p>你好,程序员们!这篇文章是关于 Flask 静态文件及其实现的。所以让我们开始吧!</p> <h2 id="对-flask-中静态文件的需求"><strong>对 Flask 中静态文件的需求</strong></h2> <p>你会发现几乎所有的网站都由照片、背景颜色和许多其他美化元素组成。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/55da3981936637d5b17b3bb63c8bfc85.png" alt="Airbnb Website Example" loading="lazy"></p> <p>Airbnb webstite Example</p> <p>网站的这种美学本质是通过使用静态文件实现的,静态文件由图像、CSS 文件和 JS 脚本组成。</p> <p>我们将这些静态文件保存在一个名为 <strong>static</strong> 的独立文件夹中,该文件夹位于我们的主 Flask 应用程序旁边。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/2ded22fbdc01de51833961b14af5eda2.png" alt="Static" loading="lazy"></p> <p>Static</p> <p>现在我们已经有了一些关于静态文件的知识,让我们看看如何实现它们。</p> <h2 id="动手操作烧瓶静态文件"><strong>动手操作烧瓶静态文件</strong></h2> <p>我们现在将使用 Flask 在我们的网页上显示背景静态文件图像。</p> <h3 id="1编写我们的主要应用程序">1.编写我们的主要应用程序</h3> <p>考虑下面的 Flask 应用程序代码</p> <pre><code class="language-py">from flask import Flask,render_template app = Flask(__name__) @app.route('/blog') def blog(): return render_template('blog.html') app.run(host='localhost', port=5000) </code></pre> <p>这里我们使用 <strong>render_template</strong> 函数渲染一个 HTML <a href="https://www.askpython.com/python-modules/flask/flask-templates" target="_blank">模板</a>。</p> <p>如果你在理解应用程序语法上有任何困难,请查看我们的<a href="https://www.askpython.com/python-modules/flask/create-hello-world-in-flask" target="_blank">Flask</a>介绍文章以获得更好的理解。</p> <h3 id="2编写我们的模板">2.编写我们的模板</h3> <p>这里我们使用特殊的 URL 属性来指定静态文件的位置。</p> <pre><code class="language-py"><img src = "{{ url_for('static',filename="<filename>") }}> </code></pre> <p>属性的<strong>URL _ 拉出位于</strong>静态<strong>文件夹内的</strong>文件<strong>的</strong>路径<strong>。</strong></p> <p>您可以下载下面的演示图片,并将其保存在<em>静态</em>文件夹中。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a0decfdd7a93aaf9d92ca819e2903455.png" alt="Blog" loading="lazy"></p> <p>Blog</p> <p>现在创建一个“<strong>blog.html</strong>”模板文件,并在其中添加以下代码:</p> <pre><code class="language-py"><html> <body> <img src= "{{ url_for('static',filename='blog.jpg') }}"> <h2>This is a blog website</h2> </body> </html> </code></pre> <p>请查看我们的 <a href="https://www.askpython.com/python-modules/flask/flask-templates" target="_blank">Flask 模板</a>文章,了解更多关于 Flask 中渲染模板的信息</p> <h3 id="3代码的实现"><strong>3。代码的实现</strong></h3> <p>就是这样;让我们现在运行服务器并检查我们的网页</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/466519af62dc84eecce2a025789262a8.png" alt="Static Website" loading="lazy"></p> <p>Static Website</p> <p>完美!!</p> <h2 id="结论-2"><strong>结论</strong></h2> <p>本教程到此为止,各位!我希望这篇文章能帮助你提高对 Flask 中静态文件的认识。请查看我们的 Flask 模板文章,了解更多关于模板的信息。</p> <p>下一篇文章再见!到那时,快乐的编码!!</p> <h1 id="flask-模板在-python-flask-中设置模板">Flask 模板–在 Python Flask 中设置模板</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/flask/flask-templates" target="_blank">https://www.askpython.com/python-modules/flask/flask-templates</a></p> </blockquote> <p>嘿伙计们!!欢迎来到我们烧瓶系列的另一个教程。在这篇文章中,我们将了解到 <a href="https://www.askpython.com/python-modules/flask" target="_blank">Flask web 框架</a>中的模板以及如何使用它们。所以让我们开始吧!</p> <h2 id="什么是模板"><strong>什么是模板?</strong></h2> <p>模板是用来在网站上显示内容的 HTML、CSS、JS 文件。模板美化了网页,让它们看起来更像样。</p> <p>因此,所有的网站包括前端(由模板组成)和后端(烧瓶框架代码和应用程序)</p> <h2 id="web-模板系统">Web 模板系统</h2> <p>web 模板系统包括模板引擎、数据源和模板处理器。</p> <p>在许多情况下,网站还会在其网页上显示数据库中的数据。Web 模板系统就是这样做的。它将来自文件/DB 和 HTML(使用模板语言)的数据组合起来,然后显示在网页上。</p> <p><strong>网页模板系统的具体工作如下:</strong></p> <ol> <li>从数据库中提取所需的数据</li> <li>使用模板引擎将数据合并到 HTML 文件中(使用模板语言)</li> <li>模板处理器然后处理它并输出结果模板文件</li> </ol> <p>Flask 使用 <strong>Jinja2</strong> 作为其默认的<strong>模板引擎</strong>。我们将在下一节进一步研究它。</p> <h2 id="神牙模板语言jtl"><strong>神牙模板语言(JTL)</strong></h2> <p>模板引擎提供了一种模板语言,我们可以用它将数据添加到 HTML 文件中。</p> <p>Jinja2 是一种现代的、设计者友好的 python 模板语言,模仿 Django 的模板。</p> <p>我们现在将看到这个模板语言的语法。它包括 4 种类型:</p> <table> <thead> <tr> <th>类型</th> <th>句法</th> </tr> </thead> <tbody> <tr> <td><strong>1)语句标签</strong></td> <td><strong>{% %}:</strong> {% if…..else % }–</td> </tr> <tr> <td><strong>2)变量标签</strong></td> <td><strong>{{ }}:</strong> {{ variable }}</td> </tr> <tr> <td><strong>3)评论标签</strong></td> <td><strong>{# ...-什么#:# t1 # # comment ... #。到#}</strong></td> </tr> <tr> <td><strong>4)行注释标签</strong></td> <td><strong>#:</strong>#注释行</td> </tr> </tbody> </table> <p>Jinja2 Templating Language</p> <h2 id="在我们的应用程序中添加模板"><strong>在我们的应用程序中添加模板</strong></h2> <p>Flask 搜索存储在主应用程序文件旁边名为–<strong>templates</strong>的文件夹中的模板。因此,在我们进入下一部分之前,请创建该文件夹。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5d1d4c282978b8bcd621a514db3cad8a.png" alt="Templates Folder" loading="lazy"></p> <p>Templates Folder</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/14b38fd7031b22dd1d65fa5f69669568.png" alt="Image 15" loading="lazy"></p> <p>Contents of the templates folder</p> <h3 id="1-render_template-函数">1. <strong>Render_template()</strong> 函数</h3> <p>Flask 应用程序使用函数 render_template()呈现模板</p> <p>语法是:</p> <pre><code class="language-py">render_template('<template_file_name.html>', variables = <values> ) </code></pre> <h3 id="2编写我们的烧瓶应用程序">2.<strong>编写我们的烧瓶应用程序</strong></h3> <p>将代码添加到您的文件 flask 主文件中(<a href="https://www.askpython.com/python-modules/flask/create-hello-world-in-flask" target="_blank">参见 flask 简介</a></p> <pre><code class="language-py">from flask import Flask, render_template app = Flask(__name__) @app.route('/blogs/<int:id>') def blogs(id): return render_template('blog.html', number=id) app.run(host='localhost', port=5000) </code></pre> <p>创建模板<strong>blog.html</strong>:</p> <pre><code class="language-py"><html> <body> <h1>This is a Blog Webpage</h1> <h2>Blog {{number}}</h1> <h3>Test Blog</h1> </body> </html> </code></pre> <p><strong>注意</strong>我们如何使用 jinja2 语言的变量标签。</p> <h3 id="3运行烧瓶应用程序">3.<strong>运行烧瓶应用程序</strong></h3> <p>运行服务器,点击网址</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a76e5dcffa25ed0dfa24953ba2c587cc.png" alt="Blog 2" loading="lazy"></p> <p>Blog 2</p> <p>瞧啊。</p> <h2 id="结论-3"><strong>结论</strong></h2> <p>就这些了,伙计们,这篇文章!这都是关于烧瓶模板。为了更好的理解,试着自己做上面的例子。到那时,快乐的编码!!</p> <h1 id="flask-用户认证如何在-flask-中设置用户登录">Flask 用户认证–如何在 Flask 中设置用户登录?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/flask/flask-user-authentication" target="_blank">https://www.askpython.com/python-modules/flask/flask-user-authentication</a></p> </blockquote> <p>在本文中,我们将使用 Flask-Login 库和 SQLAlchemy 对 Flask 用户认证进行编码。所以让我们开始吧!</p> <p>如今,几乎所有的网站都内置了用户认证系统。我们可以直接或通过像谷歌,脸书第三方用户认证设置一个帐户。苹果等。</p> <p>典型的用户登录页面如下所示:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c2effc354988e3a6f230a7923948ea0e.png" alt="Django User Authentication - Allow Signup and Login Using Django - AskPython" loading="lazy"></p> <p>User Login Page</p> <p>用户认证是网页的重要部分,因为它保护用户数据,只有特定用户才能访问它。有不同的方法来验证用户:</p> <ol> <li>基于 Cookie 的身份验证</li> <li>基于令牌的认证</li> <li>OAuth 认证</li> <li>OpenId</li> <li>安全声明标记语言(Security Assertion Markup Language 的缩写)</li> </ol> <p>我们现在将使用 Flask-Login 身份验证进行编码。所以让我们深入到编码部分。</p> <h2 id="动手使用-flask-用户验证"><strong>动手使用 Flask 用户验证</strong></h2> <p><strong>Flask-login</strong> 使用基于 Cookie 的认证。当客户端通过他的凭证登录时,Flask 创建一个包含<strong>用户 ID</strong> 的会话,然后通过 cookie 将<strong>会话 ID</strong> 发送给用户,用户可以使用它在需要时登录和退出。</p> <p>首先我们需要安装<strong>烧瓶-登录</strong></p> <pre><code class="language-py">pip install flask-login </code></pre> <p>现在已经安装好了,让我们进入编码部分!</p> <h2 id="1编码-modelspy-文件">1.编码 models.py 文件</h2> <p>首先,我们将创建<strong>用户模型</strong>来存储用户凭证。我们将使用 Flask_SQLAlchemy 和 SQLite 数据库来完成这项工作。</p> <p>这里需要注意的一件重要事情是<strong>我们不能将用户密码</strong>直接保存在数据库中,因为如果某个黑客进入我们的网站,他将能够从数据库中检索所有信息。</p> <p>所以我们负担不起。但是不要担心,Flask werkzeug 有内置的函数来处理这个问题。</p> <h3 id="11-设置密码哈希">1.1 设置密码哈希</h3> <p>解决方案是使用一个<strong>密码散列</strong>。让我们看看什么是散列,因此在终端中进入 python shell 并运行命令</p> <pre><code class="language-py">from werkzeug.security import generate_password_hash a = generate_password_hash('1234') print(a) </code></pre> <p>我们将得到一个长的随机字符串,如下所示:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/db4204ee9a17bd53f1318dfb79f12cde.png" alt="Password Hash" loading="lazy"></p> <p>Password Hash</p> <p>因此,即使黑客能够访问它们,他也无法解密。此外,我们还有另一个函数来比较哈希和密码,称为 <strong>check_password_hash</strong> 。</p> <p>它的工作原理如下:</p> <pre><code class="language-py">from werkzeug.security import generate_password_hash, check_password_hash a = generate_password_hash('1234') print(a) chech_password_hash(a,'1234') </code></pre> <p>现在点击回车键,如果匹配将返回<strong>真</strong>,如果不匹配将返回<strong>假</strong>。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f6728ee76e10a0298f8d04dccd4e6858.png" alt="Password Hash" loading="lazy"></p> <p>Password Hash</p> <h3 id="12-向数据库添加哈希密码">1.2 向数据库添加哈希密码</h3> <p>同样,如果你没有<a href="https://www.askpython.com/python-modules/flask/flask-postgresql" target="_blank">烧瓶炼金术</a>,只需使用 <a href="https://www.askpython.com/python-modules/python-pip" target="_blank">pip 命令</a>安装即可:</p> <pre><code class="language-py">pip install flask-sqlalchemy </code></pre> <p>好了,现在 SQLAlchemy 已经就绪,创建一个文件 <strong>models.py</strong> 并添加代码:</p> <pre><code class="language-py">from flask_sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin db = SQLAlchemy() class UserModel(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(80), unique=True) username = db.Column(db.String(100)) password_hash = db.Column(db.String()) def set_password(self,password): self.password_hash = generate_password_hash(password) def check_password(self,password): return check_password_hash(self.password_hash,password) </code></pre> <p>这里:</p> <ul> <li>我们正在存储<strong>电子邮件</strong>、<strong>用户名、</strong>和密码散列</li> <li>此外,我们将定义两个类方法——<strong>set _ password</strong>来生成密码散列,以及 <strong>check_password</strong> 来比较它们</li> </ul> <p>我们还使用 flask_login 库中的 UserMixin。UserMixin 有一些内置函数,我们稍后会用到:</p> <ul> <li><strong>is_authenticated:</strong> 如果用户拥有有效凭证,则返回 <strong>True</strong></li> <li><strong>is_active:</strong> 如果用户的账户是活动的,则返回 <strong>True</strong> 。Instagram 上所有被禁用的账户将返回<strong>错误。</strong></li> <li><strong>is_anonymous:</strong> 为普通用户返回 <strong>False</strong> ,为首次用户/匿名用户返回 <strong>True</strong></li> <li><strong>get_id():</strong> 以字符串形式返回用户的唯一标识符。</li> </ul> <h3 id="13设置-flask_login-扩展">1.3.设置 Flask_login 扩展</h3> <p>此外,我们需要创建并初始化 Flask_login 扩展。我们使用代码:</p> <pre><code class="language-py">from flask_login import LoginManager #... login = LoginManager() #... </code></pre> <p>正如我们前面讨论的,Flask 在会话中存储登录用户的用户 ID 。由于 Flask_Login 对数据库一无所知,我们需要创建一个函数来链接这两个数据库。</p> <p>这是使用<strong>用户加载器</strong>功能完成的。语法是:</p> <pre><code class="language-py">from flask_login import LoginManager login = LoginManager() @login.user_loader def load_user(id): return UserModel.query.get(int(id)) </code></pre> <h3 id="14完全码">1.4.完全码</h3> <p><strong>models.py</strong> 部分到此为止。让我们只看一下整个代码:</p> <pre><code class="language-py">from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from flask_login import LoginManager login = LoginManager() db = SQLAlchemy() class UserModel(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(80), unique=True) username = db.Column(db.String(100)) password_hash = db.Column(db.String()) def set_password(self,password): self.password_hash = generate_password_hash(password) def check_password(self,password): return check_password_hash(self.password_hash,password) @login.user_loader def load_user(id): return UserModel.query.get(int(id)) </code></pre> <p>如果你不熟悉 Flask SQLAlchemy,一定要看看我们的文章。</p> <h2 id="2编写我们的主-flask-应用程序文件">2.编写我们的主 Flask 应用程序文件</h2> <p>现在让我们编写主要的 <a href="https://www.askpython.com/python-modules/flask/create-hello-world-in-flask" target="_blank">Flask 应用程序</a>文件。</p> <pre><code class="language-py">from flask import Flask app =Flask(__name__) app.run(host='localhost', port=5000) </code></pre> <h3 id="21-将数据库链接到我们的-flask-文件">2.1 将数据库链接到我们的 Flask 文件</h3> <p>好了,现在我们需要将 SQLite 数据库与 SQLALchemy 连接起来。因此,添加代码:</p> <pre><code class="language-py">from flask import Flask app =Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.run(host='localhost', port=5000) </code></pre> <p>只需将 <strong>< db_name ></strong> 替换成你想要的任何名字。此外,我们需要将我们的 SQLAlchemy DB 实例(存在于 <strong>models.py</strong> 文件中)与主应用程序链接起来。为此,添加:</p> <pre><code class="language-py">from flask import Flask from models import db app =Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) app.run(host='localhost', port=5000) </code></pre> <p>现在,我们必须在第一个用户请求之前添加创建数据库文件的代码。我们的做法如下:</p> <pre><code class="language-py">from flask import Flask from models import db app =Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) @app.before_first_request def create_table(): db.create_all() app.run(host='localhost', port=5000) </code></pre> <p>现在 DB 部分的一切都结束了。现在让我们转到 Flask_login 部分</p> <h3 id="22-向我们的应用添加用户认证">2.2 向我们的应用添加用户认证</h3> <p>类似于 DB 实例,我们也必须将<strong>登录</strong>实例链接到我们的应用程序。我们通过以下方式实现:</p> <pre><code class="language-py">from flask import Flask from models import login app =Flask(__name__) login.init_app(app) app.run(host='localhost', port=5000) </code></pre> <p>之后,我们告诉 Flask_login 关于页面的情况;未经身份验证的用户将被重定向,这只是登录页面本身。</p> <p>因此添加代码:</p> <pre><code class="language-py">from flask import Flask from models import login app =Flask(__name__) login.init_app(app) login.login_view = 'login' app.run(host='localhost', port=5000) </code></pre> <p>提到重定向页面后,我们可以简单地将 <strong>@login_required</strong> 装饰器添加到所有需要认证的网页视图中。</p> <p>酷!现在唯一剩下的是<strong>登录、注册和注销</strong>视图。但在此之前,让我们编写一个简单的页面,用户可以在认证后看到它</p> <h3 id="23-简单视图的编码">2.3 简单视图的编码</h3> <p>因此添加一个简单的视图:</p> <pre><code class="language-py">from flask import Flask, render_template from flask_login import login_required @app.route('/blogs') @login_required def blog(): return render_template('blog.html') </code></pre> <p>注意我们是如何使用 <strong>@login_required</strong> 装饰器的。blog.html 的<strong>模板将是:</strong></p> <pre><code class="language-py"><h2>Welcome to the Blog</h2> <h3>Hi {{ current_user.username }}</h3> <a href="{{ url_for('logout')}}">Logout Here</a> </code></pre> <p>请查看我们的<a href="https://www.askpython.com/python-modules/flask/flask-templates" target="_blank">烧瓶模板</a>文章,了解更多关于模板的信息。</p> <h3 id="23-对登录视图编码">2.3 对登录视图编码</h3> <p>登录视图会很简单。它应该执行以下操作:</p> <ul> <li>如果用户已经通过身份验证,重定向到博客页面,否则显示一个 HTML 表单</li> <li>从数据库中检索用户信息</li> <li>比较凭据,如果正确,重定向到博客页面</li> </ul> <p>所以添加代码:</p> <pre><code class="language-py">from flask import Flask, request, render_template from flask_login import current_user, login_user @app.route('/login', methods = ['POST', 'GET']) def login(): if current_user.is_authenticated: return redirect('/blogs') if request.method == 'POST': email = request.form['email'] user = UserModel.query.filter_by(email = email).first() if user is not None and user.check_password(request.form['password']): login_user(user) return redirect('/blogs') return render_template('login.html') </code></pre> <p>和<strong>login.html</strong>模板:</p> <pre><code class="language-py"><form action="" method = "POST"> <p>email <input type = "email" name = "email" /></p> <p>password <input type = "password" name = "password" /></p> <p> submit <input type = "submit" value = "Submit" /></p> </form> <h3>Dont Have an account??</h3> <h3><a href = "{{url_for('register') }}">Register Here</a></h3> </code></pre> <h3 id="24-寄存器视图编码">2.4 寄存器视图编码</h3> <p>注册视图应该能够执行以下操作:</p> <ul> <li>如果用户已经通过身份验证,重定向到博客页面,否则显示一个 HTML 表单</li> <li>将用户数据添加到数据库</li> <li>重定向至登录页面</li> </ul> <p>所以代码将是:</p> <pre><code class="language-py">from flask import Flask, request, render_template from flask_login import current_user @app.route('/register', methods=['POST', 'GET']) def register(): if current_user.is_authenticated: return redirect('/blogs') if request.method == 'POST': email = request.form['email'] username = request.form['username'] password = request.form['password'] if UserModel.query.filter_by(email=email): return ('Email already Present') user = UserModel(email=email, username=username) user.set_password(password) db.session.add(user) db.session.commit() return redirect('/login') return render_template('register.html') </code></pre> <p>因此,<strong>register.html</strong>页面将会是:</p> <pre><code class="language-py"><form action="" method = "POST"> <p>email <input type = "email" name = "email" /></p> <p>Username <input type = "text" name = "username" /></p> <p>password <input type = "password" name = "password" /></p> <p> submit <input type = "submit" value = "Submit" /></p> </form> <h3>Already Have an Account?</h3><br> <h3><a href ="{{url_for('login')}}">Login Here</a></h3> </code></pre> <h3 id="25-对注销视图进行编码">2.5 对注销视图进行编码</h3> <p>注销视图应该只是让用户注销。因此添加代码:</p> <pre><code class="language-py">from flask import Flask, render_template from Flask_login import logout_user @app.route('/logout') def logout(): logout_user() return redirect('/blogs') </code></pre> <p>就是这样!!因此,让我们看一下这一部分的完整代码:</p> <pre><code class="language-py">from flask import Flask,render_template,request,redirect from flask_login import login_required, current_user, login_user, logout_user from models import UserModel,db,login app = Flask(__name__) app.secret_key = 'xyz' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) login.init_app(app) login.login_view = 'login' @app.before_first_request def create_all(): db.create_all() @app.route('/blogs') @login_required def blog(): return render_template('blog.html') @app.route('/login', methods = ['POST', 'GET']) def login(): if current_user.is_authenticated: return redirect('/blogs') if request.method == 'POST': email = request.form['email'] user = UserModel.query.filter_by(email = email).first() if user is not None and user.check_password(request.form['password']): login_user(user) return redirect('/blogs') return render_template('login.html') @app.route('/register', methods=['POST', 'GET']) def register(): if current_user.is_authenticated: return redirect('/blogs') if request.method == 'POST': email = request.form['email'] username = request.form['username'] password = request.form['password'] if UserModel.query.filter_by(email=email).first(): return ('Email already Present') user = UserModel(email=email, username=username) user.set_password(password) db.session.add(user) db.session.commit() return redirect('/login') return render_template('register.html') @app.route('/logout') def logout(): logout_user() return redirect('/blogs') </code></pre> <p><strong>user model . query . filter _ by(email = email)。first()</strong> 将返回它从数据库中获得的第一个用户,或者如果没有找到用户,将返回 <strong>None</strong> 。</p> <h2 id="flask-用户认证应用程序的实现">Flask 用户认证应用程序的<strong>实现</strong></h2> <p>让我们最后测试一下我们的应用程序。运行烧瓶文件:</p> <pre><code class="language-py">python filename.py </code></pre> <p>并且尽量去“<strong>/博客</strong>”。你将被重定向到<strong>登录</strong>页面。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/47f449b05a0894a35d87ced6c5eb46a2.png" alt="Login " loading="lazy"></p> <p>Login</p> <p>点击注册,然后添加您的详细信息。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/279556b09381ba86500b51d891b1803e.png" alt="Register" loading="lazy"></p> <p>Register</p> <p>点击提交,你将回到登录页面。这一次输入您的凭证并登录。您将看到博客页面!!</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/9011c65ff01a796674dc38491a6fedb2.png" alt="Blogs" loading="lazy"></p> <p>Blogs</p> <p><strong>注意:</strong>使用简单的电子邮件,如 <strong><a href="/cdn-cgi/l/email-protection" target="_blank">【电子邮件保护】</a></strong> 可能会在 Chrome 浏览器中出现如下所示的错误。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1eb43c1c0457cc29b66107c0281f5c4c.png" alt="Redirect To Blog Successful Login" loading="lazy"></p> <p>Redirect To Blog Successful Login</p> <p>如您所见,我们已经被重定向到“博客”端点。我在上面的截图中弹出了一条安全信息,因为我使用了一个随机的不存在的非常弱的密码。</p> <p>你可以用一个更强的密码和一个好的电子邮件地址做同样的尝试,你会直接看到博客页面,而不是在这种情况下的安全警告。</p> <h2 id="结论-4"><strong>结论</strong></h2> <p>就这样,伙计们!这都是关于 Flask 中的用户认证。一定要看看我们的<a href="https://www.askpython.com/python-modules/flask/flask-sessions" target="_blank">烧瓶会议</a>和<a href="https://www.askpython.com/python-modules/flask/flask-cookies" target="_blank">饼干</a>文章,以了解它们是如何工作的。</p> <p>在下一篇文章中,我们将把我们的应用程序部署到云服务器上。</p> <h1 id="flask-vs--djangodjango-和-flask-之间的快速比较">Flask vs . Django–Django 和 Flask 之间的快速比较</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/flask-vs-django" target="_blank">https://www.askpython.com/python-modules/flask-vs-django</a></p> </blockquote> <p>大家好。!在本文中,我们将遇到 Flask 和 Django 之间的一些主要差异。所以让我们开始吧!!</p> <h2 id="什么是-django-">什么是 <strong>Django</strong> ?</h2> <p>Django 是一个广泛的 web 框架,旨在简化 web 开发过程。它是一个基于 <a href="https://www.askpython.com/django/django-mvt-architecture" target="_blank">MVT 模型视图模板</a>架构的开源 python web 开发框架。</p> <p>它关注于可重用的组件、更少的代码和快速开发。另外,Django 有自己的 <strong>ORM</strong> (对象关系映射)系统。</p> <p>也就是说,它与 <a href="https://www.askpython.com/django/django-models" target="_blank"><strong>模型</strong></a> (具有类似于数据库表的结构)一起工作,并用于将 DB 表与其余应用程序代码链接起来。</p> <p>Django 应用程序有一个目录结构,最适合大规模的 web 项目(如电子商务、社交媒体等)。)</p> <h2 id="什么是烧瓶">什么是<strong>烧瓶</strong>?</h2> <p>Flask 是一个基于 python 编程语言构建的微型 web 框架,拥有最少的 web 开发工具。因此,它为可定制性提供了更大的空间,这意味着它拥有极简的内置包,并且没有任何限制。开发者可以自由使用任何他们想要的第三方库。</p> <p>Flask】不提供它的 <strong>ORM</strong> ,因此根本没有模型,不像 Django。</p> <p>Flask 应用程序通常是单页应用程序(SPA ),通常用于中小型网络项目,如博客等。)</p> <h2 id="比较-flask-和-django-的差异"><strong>比较 Flask 和 Django 的差异</strong></h2> <p>基本区别是:</p> <table> <thead> <tr> <th>姜戈</th> <th>瓶</th> </tr> </thead> <tbody> <tr> <td><strong>广泛的 web 框架</strong>:基于 Python 的全功能架构,具有 MVT 架构。它有很好的文档。</td> <td>Micro web framework: 它有基于 Python 的极简内置包。轻,简单和可定制的框架。这是初学者友好的。</td> </tr> <tr> <td><strong>提供 ORM 系统:</strong>预建 ORM 系统。因此,使用数据库更加简单</td> <td><strong>无 ORM 系统:</strong>没有预建 ORM 系统,也根本没有模型。它有其他方法来处理数据库。</td> </tr> <tr> <td><strong>基于目录的</strong> <strong>结构</strong>:它有一个合适的基于目录的设计,包括所有的模型、视图、URL 和模板等。分别存储在单独的文件中。</td> <td><strong>更模块化的结构:</strong>用于构建单页应用(spa),具有模块化结构。因此,所有的观点,网址等可以存储在同一个文件。</td> </tr> <tr> <td><strong>更重要的社区:</strong>它比 Flask 更早就在市场上立足。因此比 Flask 拥有更大的社区支持。</td> <td><strong>更小的群体:</strong>与 Django 相比,它在市场上相当新,因此与 Django 相比,它获得的群体支持相对较少。</td> </tr> <tr> <td><strong>内置包:</strong>它是完全加载的,即所有的库都已经内置,因此不需要安装/导入第三方包。因此可以轻松使用多种功能。</td> <td>可定制:它更加灵活,因此只有最少的内置包。因此给了开发者建造的空间。</td> </tr> <tr> <td>安全性: Django 提供了几个内置选项来保护应用程序免受伪造。</td> <td>安全: Flask-Security 包也提供了类似的选项来保护应用程序免受互联网伪造。</td> </tr> <tr> <td><strong>大型项目:</strong>适合大型和广泛的项目</td> <td><strong>中小型项目:</strong>适合中小型项目</td> </tr> </tbody> </table> <h2 id="结论-5">结论</h2> <p>就这样,伙计们!既然 Flask 和 Django 之间的区别已经很清楚了,那么您可以根据您要构建的项目来选择使用什么框架。下次见!编码快乐!</p> <h1 id="烧瓶-wt-表格">烧瓶 WT 表格</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/flask/flask-wt-forms" target="_blank">https://www.askpython.com/python-modules/flask/flask-wt-forms</a></p> </blockquote> <p>欢迎来到本教程!今天我们将研究 Flask web 框架中的一个表单库,称为 Flask WT Forms。</p> <h2 id="对烧瓶-wt-形式的需求"><strong>对烧瓶 WT 形式的需求</strong></h2> <p>虽然 HTML 表单可以使用,但是它们有一些缺点:</p> <ul> <li>在客户端 HTML 表单和服务器端 Flask 应用程序之间没有直接链接。也就是说,表单数据与请求对象一起从客户端(用户)发送到服务器端。因此 Flask View 必须重新创建表单元素来处理它们。</li> <li>HTML 表单很难实时动态呈现。</li> <li>HTML 表单不提供验证用户输入的方法。</li> </ul> <p>因此,在我们的应用程序代码中最好使用 Flask WT 表单。</p> <h2 id="建立烧瓶-wt-表单"><strong>建立烧瓶 WT 表单</strong></h2> <p>理解它的最好方法是我们自己去尝试。在本节中,我们将做到这一点!所以系好安全带,让我们开始吧。</p> <h3 id="1将-ing-wt-表单安装到您的系统中">1.<strong>将</strong> ing WT 表单安装到您的系统中</h3> <p>要使用 WT 表单,我们必须首先安装它。这里我们使用 <a href="https://www.askpython.com/python-modules/python-pip" target="_blank">PIP</a> 来安装它。因此,在您的终端中,运行命令</p> <pre><code class="language-py">pip install flask-wtf </code></pre> <p>好了,现在我们可以使用它了。</p> <h3 id="2在-formspy-文件中编写一个简单的-wt-表单"><strong>2。在 Forms.py 文件中编写一个简单的 WT 表单</strong></h3> <p>WT 表格应存在于单独的“ <strong>forms.py</strong> ”文件中。因此,在主烧瓶文件旁边创建一个新的 <strong>forms.py</strong> 文件。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/b5059fc31fb21feacc5180877cd2a9f8.png" alt="File Location" loading="lazy"></p> <p>File Location</p> <p>WT 格式的语法如下所示:</p> <pre><code class="language-py">from flask_wtf import Form from wtforms import Field1, Field2, Field3 ......, SubmitField class FormName(Form): Fied1_name = Field1("Display_name") Fied2_name = Field2("Display_name") Fied3_name = Field3("Display_name") submit = SubmitField("Submit") </code></pre> <p>这里,表单类中的字段可以是:</p> <table> <thead> <tr> <th>表单字段</th> <th>描述</th> </tr> </thead> <tbody> <tr> <td><strong>文本字段</strong></td> <td>它类似于 HTML 表单属性中的输入类型–<strong>文本</strong></td> </tr> <tr> <td><strong>布尔字段</strong></td> <td>它类似于 HTML 表单属性中的输入类型–<strong>复选框</strong></td> </tr> <tr> <td><strong>十进制字段</strong></td> <td>它是显示带小数位的数字的文本字段</td> </tr> <tr> <td><strong>整数文件</strong></td> <td>这是显示整数的文本字段</td> </tr> <tr> <td><strong>无线电场</strong></td> <td>它指示单选按钮 HTML 表单元素</td> </tr> <tr> <td><strong>选择字段</strong></td> <td>它指示选择表单元素</td> </tr> <tr> <td><strong>文本区域字段</strong></td> <td>它类似于 HTML 表单属性中的输入类型-文本区域</td> </tr> <tr> <td><strong>密码字段</strong></td> <td>它将密码作为用户输入的表单。</td> </tr> <tr> <td><strong>提交字段</strong></td> <td>它类似于 HTML 表单属性中的输入类型–<strong>Submit</strong></td> </tr> </tbody> </table> <p>Form Fields</p> <p>我们还可以在表单域中添加验证器。现在让我们在 forms.py 文件中编写一个简单的学生表单:</p> <pre><code class="language-py">from flask_wtf import Form from wtforms import TextField, IntegerField, SubmitField from wtforms import validators, ValidationError class StudentForm(Form): name = TextField("Student Name", [validators.Required("Please enter your name")]) marks = IntegerField("Marks", [validators.Required("Please enter your marks")]) email = TextField("Email",[validators.Required("Please enter your email"),validators.Email("Invalid email address")]) submit = SubmitField("Submit") </code></pre> <p>如果您的设备中没有安装 <strong>email_validator</strong> ,您可能会得到一个错误。要解决这个问题,只需安装 <strong>email_validator</strong> :</p> <pre><code class="language-py">pip install email_validator </code></pre> <p>就这样,现在可以工作了。</p> <h3 id="3编码主烧瓶文件">3.<strong>编码主烧瓶文件</strong></h3> <p>现在,我们将把表单包含在主文件中。考虑以下代码:</p> <pre><code class="language-py">from flask import Flask,render_template, request from forms import StudentForm app = Flask(__name__) app.secret_key = 'form_csrf_token_security_key' @app.route('/form', methods = ['POST', 'GET']) def FormView(): form = StudentForm() if request.method =='POST': form = StudentForm() if form.validate()== True: return "Process Successful" return render_template('form.html', form = form) return render_template('form.html', form = form) app.run(host='localhost', port=5000) </code></pre> <p>这里:</p> <ul> <li>我们把表单称为类对象。当用户第一次打开站点时( <strong>GET</strong> 方法), <strong>StudentForm()</strong> 将为空。因此我们将得到一个空的表单。</li> <li>当他提交表单( <strong>POST</strong> 方法)时, <strong>StudentForm()</strong> 类对象现在包含了用户数据。如果数据有效,它将返回-"<strong>流程成功。</strong></li> </ul> <p>这是我们在这里使用的代码逻辑👆。</p> <p>需要<strong>密钥</strong>来解锁 HTML 表单模板中的 CSRF 安全令牌。</p> <h3 id="4为表单创建模板"><strong>4。为表单</strong>创建模板</h3> <p>现在,为了向用户显示表单,我们必须将它包含在 HTML 模板文件中。在 HTML 中包含 WT 格式的语法是:</p> <pre><code class="language-py"><form action = "http://localhost:5000/endpoint" method = post> {{ form.hidden_tag() }} {{ form.field_name1.label }}<br> {{ form.field_name1 }} <br> {{ form.field_name2.label }}<br> {{ form.field_name2 }} <br> {{ form.field_name3.label }}<br> {{ form.field_name3 }} <br> {{ form.submit }} </form> </code></pre> <p>这里,</p> <ul> <li><strong>{{ form.hidden_tag() }}</strong> 是隐藏的 CSRF 令牌字段,它获取主 Flask 应用程序文件中提到的安全密钥。</li> <li>{{ <strong>form.field.Label</strong> }}表示字段名称。</li> <li>{{ <strong>form.field</strong> }}表示字段输入框。</li> </ul> <p>因此,我们学生表单的模板文件“<strong>form.html</strong>”将是:</p> <pre><code class="language-py"><form action = "http://localhost:5000/form" method = post> {{ form.hidden_tag()}} {{ form.name.label }}<br> {{ form.name }} <br> {{ form.marks.label }}<br> {{ form.marks }} <br> {{ form.email.label }}<br> {{ form.email }} <br> {{ form.submit }} </form> </code></pre> <p>请查看我们的<a href="https://www.askpython.com/python-modules/flask/flask-templates" target="_blank">烧瓶模板</a>文章,了解更多关于模板的信息</p> <h3 id="5实施烧瓶应用程序"><strong>5。实施</strong>烧瓶应用程序</h3> <p>编码部分就这样了!!现在让我们启动服务器</p> <pre><code class="language-py">python filename.py </code></pre> <p>转到“<strong>/表格</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ca7fa5489a365cd714144278ab4c8915.png" alt="Flask WT Forms" loading="lazy"></p> <p>WT Form</p> <p>输入详细信息,然后点击提交。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3e4df5caec1b32da61316e8b3f67cad8.png" alt="Success Page" loading="lazy"></p> <p>Success Page</p> <p>不错!!</p> <h2 id="结论-6"><strong>结论</strong></h2> <p>就这样,伙计们!!这都是关于烧瓶 WT 的形式。请查看我们的 <a href="https://www.askpython.com/python-modules/flask/flask-forms" target="_blank">Flask Forms</a> 文章,了解更多关于 Flask HTML 表单的信息。要了解更多关于 Flask WT 表单的信息,请在这里阅读<a href="https://flask.palletsprojects.com/en/2.0.x/" target="_blank">文档</a>。</p> <p>我们将在下一篇文章中看到你们。到那时,快乐的编码!!</p> <h1 id="python-fpdf-模块如何将数据和文件转换成-pdf">Python fpdf 模块——如何将数据和文件转换成 pdf?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/fpdf-module-convert-to-pdf" target="_blank">https://www.askpython.com/python-modules/fpdf-module-convert-to-pdf</a></p> </blockquote> <p>读者朋友们,你们好!在本文中,我们将学习使用 Python 中的 fpdf 模块将文本数据和文件转换成 pdf 格式。</p> <p>所以,让我们开始吧!</p> <hr> <h2 id="使用-fpdf-模块将数据文件转换为-pdf">使用 fpdf 模块将数据/文件转换为 pdf</h2> <p>Python 为我们提供了大量的库来执行实时转换,并通过自动化来解决现实生活中的问题。</p> <p>当涉及到数据传输或将数据转换成特定格式的文件时,Python 确实为我们提供了一些执行这些操作的函数。</p> <p>使用 Python,我们可以自动完成将数据转换和存储为 PDF 表单的整个过程。使用 Python 中的 fpdf 模块,这是可能的。</p> <p>当我们想要自动将数据直接传输到 pdf 而不需要任何手动干预时,这种情况很有帮助。您甚至可以将文件发送到系统本地的特定存储位置,甚至可以发送到一些公共、私有云存储上。</p> <p>今天,在本文中,我们将使用 Python 中的 fpdf 模块执行以下两项任务:</p> <ul> <li><strong>将脚本生成的文本数据存储为 PDF 格式。</strong></li> <li><strong>将文本文件转换成 PDF 格式。</strong></li> </ul> <p>所以,让我们开始吧!</p> <hr> <h2 id="1将数据存储为-pdf-格式">1.将数据存储为 PDF 格式</h2> <p>最初,在本节中,我们尝试将脚本生成的文本数据存储到 PDF 表单的特定位置。</p> <p>为了达到同样的目的,我们必须从 fpdf 模块中导入 FPDF 类。此外,我们需要在 pdf 中创建一个页面,以便在其上打印数据。这可以使用 add_page()方法来实现。函数的作用是:设置文本的属性,比如文本的字体,字母的大小等等。</p> <p>创建页面后,我们现在使用 cell()函数来设置分页的宽度和高度,并设置要粘贴到新创建的 pdf 文件中的数据。</p> <p>最后,我们使用 output()函数将数据打印到所创建的 PDF 文件中的指定位置。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size = 25) # create a cell pdf.cell(200, 10, txt = "JournalDev", ln = 1, align = 'C') pdf.cell(200, 10, txt = "Welcome to the world of technologies!", ln = 2, align = 'C') pdf.output("data.pdf") </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/46c59b3c53d0aa89f379a821a47b0591.png" alt="Text To PDF" loading="lazy"></p> <p>Text To PDF</p> <hr> <h2 id="2python-中文本文件到-pdf-文件的转换">2.Python 中文本文件到 PDF 文件的转换</h2> <p>已经将脚本生成的文本文件存储为 PDF 表单,现在让我们使用 fpdf 模块将本地可用的文本文件转换为 PDF 表单。</p> <p>同样,我们需要使用 file.open()函数以“读取”模式打开文本文件。之后,我们在 for 循环中遍历数据,然后使用 cell()函数将遍历的数据存储到 PDF 表单中。</p> <p>最后,我们使用 output()函数在指定的位置以指定的名称创建设计好的 PDF。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size = 25) # create a cell file = open("data.txt", "r") # insert the texts in pdf for g in file: pdf.cell(200, 10, txt = g, ln = 1, align = 'C') pdf.output("PDF.pdf") </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/24270895af4a033a42fee68b49aa3f97.png" alt="Text File To PDF" loading="lazy"></p> <p>Text File To PDF</p> <hr> <h2 id="结论-7">结论</h2> <p>到此,我们就结束了这个话题。如果你遇到任何问题,欢迎在下面评论。</p> <p>更多与 Python 编程相关的帖子,敬请关注我们!</p> <p>在那之前,学习愉快!!🙂</p> <h1 id="python-中频率表的介绍">Python 中频率表的介绍</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/frequency-tables" target="_blank">https://www.askpython.com/python/examples/frequency-tables</a></p> </blockquote> <p>描述几个类别出现频率的表格称为<strong>频率表</strong>。这种特殊的表特别有助于了解数据集中包含的值的分布情况。本教程将带您完成用 Python 创建频率表的过程。我们将在接下来的几节中以不同的方式介绍相同的实现。</p> <p><em><strong>也读作:<a href="https://www.askpython.com/python-modules/pandas/count-pandas-dataframe-rows" target="_blank">计算熊猫数据帧行数的 6 种方法</a></strong></em></p> <hr> <h2 id="方法-1借助-value_counts函数">方法 1–借助 value_counts()函数</h2> <p>第一种方法是利用<code>value_counts()</code>函数,该函数将返回一个包含所有值列表中唯一值的计数的序列。结果将按照<code>descending</code>的顺序排列,这意味着第一个元素是最频繁出现的元素。</p> <pre><code class="language-py">import pandas as pd data = pd.Series([1, 2, 5, 2, 3, 3, 3, 3, 4, 4, 5]) print("The Dataset is : ") print(data) print("\nFrequency Table for the data : ") print(data.value_counts()) </code></pre> <pre><code class="language-py">The Dataset is : 0 1 1 2 2 5 3 2 4 3 5 3 6 3 7 3 8 4 9 4 10 5 dtype: int64 Frequency Table for the data : 3 4 2 2 5 2 4 2 1 1 </code></pre> <hr> <h2 id="方法-2借助交叉表函数">方法 2–借助<strong>交叉表</strong>()函数</h2> <p>我们可以用来显示熊猫数据帧频率的另一个函数是 <strong><code>crosstab()</code></strong> 函数,如下面的代码所示。我们将创建一个数据帧,然后为数据帧的两列创建频率表。</p> <pre><code class="language-py">df = pd.DataFrame({'Student_Grade': ['A','B','A','B','B', 'B', 'B', 'C', 'C', 'D'], 'Student_Age': [18, 25, 28, 19, 30, 20, 15, 18, 29, 17], 'Student_Gender': ['M','F', 'M', 'F', 'F', 'M', 'M', 'F', 'F', 'F']}) print("The Dataset is : ") print(df) print("\nFrequency Table for the Grade in the dataset : ") pd.crosstab(index=df['Student_Grade'], columns='count') </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/b7110a4c3aa1aff2dbe5e18fecb3ef94.png" alt="Crosstab Output Screenshot" loading="lazy"></p> <p>Crosstab Output Screenshot</p> <pre><code class="language-py">print("\nFrequency Table for the Gender in the dataset : ") pd.crosstab(index=df['Student_Gender'], columns='count') </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/473014196e744e40a200a5d70d371c21.png" alt="Crosstab Output Screenshot 2" loading="lazy"></p> <p>Crosstab Output Screenshot 2</p> <hr> <h2 id="高级频率表双向表">高级频率表(双向表)</h2> <p>我们还可以创建一个<strong>双向频率表</strong>来显示我们在上一节中使用的数据集中两个不同列的频率。下面的代码显示了两列 Age 和 Grade 的双向频率表。</p> <pre><code class="language-py">pd.crosstab(index=df['Student_Grade'], columns=df['Student_Age']) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7570c880e3335f3419d2e8658ab93f62.png" alt="Two Way Freq Table Output 1" loading="lazy"></p> <p>Two Way Freq Table Output 1</p> <p>我们还将在性别和年级两栏之间开发一个双向频率表。看看下面的代码。</p> <pre><code class="language-py">pd.crosstab(index=df['Student_Grade'], columns=df['Student_Gender']) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fbab292a7b2aa26e17798701ffdb84c7.png" alt="Two Way Freq Table Output 2" loading="lazy"></p> <p>Two Way Freq Table Output 2</p> <hr> <p>感谢您的阅读!我希望你理解了教程😃</p> <p>我建议您也阅读以下教程:</p> <ol> <li><a href="https://www.askpython.com/python/examples/calculating-precision" target="_blank">Python 中的计算精度—分类误差度量</a></li> <li><a href="https://www.askpython.com/python/examples/chi-square-test" target="_blank">Python 中的卡方检验——您需要知道的一切!!</a></li> <li><a href="https://www.askpython.com/python/numpy-trigonometric-functions" target="_blank">泛 NumPy 三角函数认识</a></li> </ol> <hr> <h1 id="用-python-解决朋友旅行问题谷歌面试问题">用 Python 解决朋友旅行问题[谷歌面试问题]</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/friends-travel-problem" target="_blank">https://www.askpython.com/python/examples/friends-travel-problem</a></p> </blockquote> <p>在本教程中,我们将了解一个非常有趣的问题,称为<strong>朋友旅行问题</strong>。我们先来了解一下,在这个问题上,我们想达到什么目的?</p> <hr> <h2 id="朋友-旅行问题解释">朋友-旅行问题解释</h2> <p>让我们假设 n 个朋友想去参加一个聚会,他们可以单独旅行,也可以结伴同行。我们假设对于 n 个朋友,有 n 辆摩托车可用。</p> <p>我们需要计算 n 个朋友可以去参加聚会的方式,可以是单独去,也可以是两人一组去。</p> <hr> <h2 id="朋友旅行问题的解决方案">朋友旅行问题的解决方案</h2> <p>人们可以使用循环和 if-else 条件手工编写简单的方法,也可以使用更快的方法,即<strong>递归</strong>方法。如果你想知道更多关于递归的知识,请阅读下面提到的教程。</p> <p><em><strong>了解更多关于递归的知识:<a href="https://www.askpython.com/python/python-recursion-function" target="_blank">Python 中的递归</a></strong></em></p> <p>为了解决一个更大的问题,你需要把一个更大的问题分解成更小的问题。但在此之前,我们先来看看 <strong>n</strong> ( 1,2,3)的较低值。</p> <p>对于 n = 1 和 n = 2,分别只有一种和两种可能的方式。对于 n = 3,我们有四种可能的情况。怎么会?</p> <p>对于 n 的每一个值,一个朋友有两种选择,要么这个朋友可以独自旅行,我们可以检查 n-1 个朋友。</p> <p>或者朋友可以从 n-1 个朋友中选择一个朋友一起旅行,然后我们检查 n-2 个朋友。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c677a29b19b2f6743bcb2424ceae0ee3.png" alt="Recursive Solution Friends Bike Problem" loading="lazy"></p> <p>Recursive Solution Friends Bike Problem</p> <hr> <h2 id="朋友自行车问题的代码实现">朋友自行车问题的代码实现</h2> <p>通过递归,代码实现非常简单。只要确保你已经理解了前面解释的解决方案。</p> <pre><code class="language-py">def count_no_ways(n): if(n<3): return n return (count_no_ways(n-1)) + ((n-1) * count_no_ways(n-2)) n = int(input("Enter the number of friends: ")) print(count_no_ways(n)) </code></pre> <hr> <p>希望问题、解决方案、代码实现对你来说已经很清楚了。感谢您阅读教程!</p> <p>快乐学习!😇</p> <hr> <h1 id="函数式编程-简介">函数式编程-简介</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/functional-programming-introduction" target="_blank">https://www.askpython.com/python/examples/functional-programming-introduction</a></p> </blockquote> <p>在本教程中,我们将学习函数式编程的基础知识,并通过一些例子了解如何用 Python 实现函数式编程。我们还将看看函数式编程的优缺点。</p> <h2 id="什么是函数式编程">什么是函数式编程?</h2> <p>函数式编程是另一种编程范例,就像过程式编程和面向对象编程一样。</p> <p>在函数式编程中,我们不是编写语句来产生输出,而是应用一系列函数来获得输出。</p> <p>它可用于最终结果和中间值或开始值彼此没有物理相关性的情况。</p> <p>为此,我们将问题分解为简单的函数,并使用一系列单一用途的函数来执行复杂的任务。</p> <h2 id="如何用-python-实现函数式编程">如何用 python 实现函数式编程?</h2> <p>为了在 Python 中实现函数式编程,我们将问题分解为纯函数,然后以声明的方式在序列中应用这些函数以产生输出。</p> <p><em><strong>纯函数是指函数的输出不应该依赖于程序的全局变量和状态,也不应该产生任何副作用</strong>。</em></p> <p>也就是说,函数式编程中使用的函数的输出应该只依赖于输入。</p> <p>在本文中,我们将使用<code>map()</code>、<code>filter()</code>和<code>reduce()</code>方法将过程程序转换成函数程序。</p> <h3 id="1pyhton-中的-map函数">1.Pyhton 中的 map()函数</h3> <p><a href="https://www.askpython.com/python/built-in-methods/map-method-in-python" target="_blank"><code>map()</code>函数</a>将一个函数作为它的第一个参数,将一个可迭代对象作为它的第二个参数,或者其后任意数量的可迭代对象。然后,在对输入 iterables 的每个元素应用函数后,它返回一个 map 对象。然后我们可以将 map 对象转换成我们想要的 iterable 类型。</p> <pre><code class="language-py">#define the function that increments a number by 1 def increment_by_one(number): return number+1 #define a list numbers= [1,3,45,67,34,78,23,56,98,104,123] print("input list to increment values by 1 is:") print(numbers) #procedural way to get a list containing incremented elements by 1 result=[] for num in numbers: result.append(increment_by_one(num)) print("Result obtained through procedural way is:") print(result) #functional way to obtain a list containing incremented elements by 1 resultbyfunc=map(increment_by_one,numbers) print("Result obtained through functional way is:") print(list(resultbyfunc)) </code></pre> <p>输出:</p> <pre><code class="language-py">input list to increment values by 1 is: [1, 3, 45, 67, 34, 78, 23, 56, 98, 104, 123] Result obtained through procedural way is: [2, 4, 46, 68, 35, 79, 24, 57, 99, 105, 124] Result obtained through functional way is: [2, 4, 46, 68, 35, 79, 24, 57, 99, 105, 124] </code></pre> <h3 id="2python-中的-filter函数">2.python 中的 filter()函数</h3> <p><a href="https://www.askpython.com/python/built-in-methods/python-filter-function" target="_blank"><code>filter()</code>函数</a>在 iterable 上应用一个函数,测试 iterable 输入的每个元素的条件,并返回 true 或 false。</p> <p>它将一个函数作为它的第一个参数,其他参数是输入函数必须应用的可迭代变量。After execution filter()还返回一个迭代器,该迭代器只迭代那些在传递给输入函数时返回 true 的输入 iterables 元素。</p> <pre><code class="language-py">#define the function that returns true when passed an even number as input def check_if_even(number): if number%2==0: return True else: return False #define a list numbers= [1,3,45,67,34,78,23,56,98,104,123] print("input list to filter even numbers is:") print(numbers) #procedural way to get a list containing even numbers from input list result=[] for num in numbers: if check_if_even(num)==True: result.append(num) print("Result obtained through procedural way is:") print(result) #functional way to obtain a list containing even numbers from input list resultbyfunc=filter(check_if_even,numbers) print("Result obtained through functional way is:") print(list(resultbyfunc)) </code></pre> <p>输出:</p> <pre><code class="language-py">input list to filter even numbers is: [1, 3, 45, 67, 34, 78, 23, 56, 98, 104, 123] Result obtained through procedural way is: [34, 78, 56, 98, 104] Result obtained through functional way is: [34, 78, 56, 98, 104] </code></pre> <h3 id="3python-中的-reduce函数">3.Python 中的 reduce()函数</h3> <p><code>reduce()</code>方法用于生成累积值,如 iterable 中所有元素的总和。它在<code>functools</code>模块中定义。</p> <p>我们可以传递一个函数,它接受两个参数并返回一个累积输出作为 reduce()的第一个参数,返回一个 iterable 作为第二个参数。</p> <p><code>reduce()</code>将 input 函数从左到右应用于输入 iterable 的项,并将 iterable 缩减为单个累积值并返回值。</p> <p>下面是一个使用过程方法和<code>reduce()</code> 函数来计算列表元素总和的例子。</p> <pre><code class="language-py">#import reduce function from functools import reduce #define the function that returns the sum of two numbers when passed as input def add(num1,num2): return num1+num2 #define a list numbers= [1,3,45,67,34,78,23,56,98,104,123] print("input list to find sum of elements is:") print(numbers) #procedural way to get the sum of numbers from input list result=0 for num in numbers: result=result+num print("Result obtained through procedural way is:") print(result) #functional way to obtain the sum of numbers from input list resultbyfunc=reduce(add,numbers) print("Result obtained through functional way is:") print(resultbyfunc) </code></pre> <p>输出:</p> <pre><code class="language-py">input list to find sum of elements is: [1, 3, 45, 67, 34, 78, 23, 56, 98, 104, 123] Result obtained through procedural way is: 632 Result obtained through functional way is: 632 </code></pre> <p>现在我们将通过一个例子来理解如何使用函数式编程。</p> <h2 id="将过程程序转换成函数程序">将过程程序转换成函数程序</h2> <p>假设给我们一个数字列表,我们必须<strong>找出列表中能被 5 整除的偶数的平方和</strong>。</p> <p>我们将使用程序性和功能性范例来实现问题的解决方案,并尝试了解程序之间的差异。</p> <p>以下是实现上述问题解决方案的程序方法。</p> <pre><code class="language-py">#define a function that returns square of a number def square(num): return num*num #define a function that checks if a number is even def is_even(num): if num%2==0: return True else: return False #define a function that checks divisibility by 5 def is_divisible_by_five(num): if num%5==0: return True else: return False #define a list numbers= [1,20,45,67,34,78,80,23,56,98,104,50,60,90,123] print("input list to find the solution is:") print(numbers) #procedural way to find the solution #extract elements which are dvisible by 5 and are even temp=[] for num in numbers: if is_even(num) and is_divisible_by_five(num): temp.append(num) #calculate square of elements in temp sqtemp=[] for num in temp: sqtemp.append(square(num)) #find sum of squared elements result=0 for num in sqtemp: result=result+num print("Result obtained through procedural way is:") print(result) </code></pre> <p>输出</p> <pre><code class="language-py">input list to find the solution is: [1, 20, 45, 67, 34, 78, 80, 23, 56, 98, 104, 50, 60, 90, 123] Result obtained through procedural way is: 21000 </code></pre> <p>现在,我们将以下面的方式在函数范例中实现上面的代码。</p> <pre><code class="language-py">#import reduce function from functools import reduce #define the function that returns sum of two numbers when passed as input def add(num1,num2): return num1+num2 #define a function that returns square of a number def square(num): return num*num #define a function that checks if a number is even def is_even(num): if num%2==0: return True else: return False #define a function that checks divisibility by 5 def is_divisible_by_five(num): if num%5==0: return True else: return False #define a list numbers= [1,20,45,67,34,78,80,23,56,98,104,50,60,90,123] print("input list to find the solution is:") print(numbers) #functional way to find the solution #filter numbers divisible by 5 temp1=filter(is_divisible_by_five,numbers) #filter even numbers temp2=filter(is_even,temp1) #find square of numbers temp3=map(square,temp2) #find sum of squares result=reduce(add,temp3) print("Result obtained through functional way is:") print(result) </code></pre> <p>输出:</p> <pre><code class="language-py">input list to find the solution is: [1, 20, 45, 67, 34, 78, 80, 23, 56, 98, 104, 50, 60, 90, 123] Result obtained through functional way is: 21000 </code></pre> <h2 id="过程编程和函数编程的区别">过程编程和函数编程的区别</h2> <ul> <li>在过程式编程中,我们使用一系列指令,这些指令使用条件运算符和循环来实现我们的示例,而我们只是通过向函数传递数据来进行函数调用,并将返回值传递给另一个函数来获得结果。在主逻辑的实现中没有使用条件运算符。</li> <li>在函数式编程中,我们使用纯函数,它们执行非常简单的操作,正如我们在示例中所做的那样,但是过程式程序中的函数可能非常复杂,并且可能有副作用。</li> <li>由于过程性程序涉及条件,它们很难调试,而函数性程序是声明性的,每个函数都有固定的工作,没有副作用,这使得它们很容易调试。</li> </ul> <h2 id="函数式编程的优势">函数式编程的优势</h2> <p>从上面的例子可以看出,下面是函数式编程的优点:</p> <ul> <li>当我们在函数式编程中使用纯函数时,调试变得很容易。</li> <li>纯函数的可重用性高,在一次调用中只完成一次操作,所以使用纯函数增加了程序的模块化。</li> <li>函数式程序的可读性很高,因为程序是声明性的,没有条件语句。</li> </ul> <h2 id="什么时候应该使用函数式编程">什么时候应该使用函数式编程?</h2> <p>函数式编程最适合做数学计算。如果你正在解决复杂的数学程序,这些程序可以分成核心步骤,函数式编程是这种情况下最好的选择。</p> <h2 id="什么时候不应该使用函数式编程">什么时候不应该使用函数式编程?</h2> <ul> <li>如果你是编程初学者,就不应该使用函数式编程。我们的大脑被训练去理解序列,最初,甚至理解程序性的程序都很困难。</li> <li>如果你正在做一个大项目,避免使用函数式编程,因为在编码阶段函数式程序的维护是困难的。</li> <li>在函数式编程中,代码的可重用性是一项非常棘手的任务,因此您需要非常擅长它,以节省您的时间和精力。</li> </ul> <h2 id="结论-8">结论</h2> <p>在本教程中,我们已经了解了什么是函数式编程,以及如何用 python 实现它。我们还看到了过程式编程和函数式编程之间的区别,函数式编程的优势,以及对于给定的任务我们是否应该使用函数式编程。</p> <h1 id="python-中的-functools-模块">Python 中的 functools 模块</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/functools-module" target="_blank">https://www.askpython.com/python-modules/functools-module</a></p> </blockquote> <p>在本文中,我们将使用 <strong>functools</strong> <strong>模块</strong>来看看 Python 中使用的一个重要函数模式。在编程中,我们经常使用高阶函数。它们是接受另一个函数作为参数并对其进行操作或返回另一个函数的函数。在 Python 中通常被称为 decorators,它们非常有用,因为它们允许对现有函数进行扩展,而无需对原始函数源代码进行任何修改。它们增强了我们的功能,并扩展它们以获得额外的功能。</p> <p><em><strong>functools</strong></em> 模块用于使用 Python 内置的高阶函数。在 Python 中,任何作为可调用对象的函数都可以被认为是使用 functools 模块的函数。</p> <h2 id="涵盖的-functools-函数列表">涵盖的 functools 函数列表</h2> <ol> <li><code>partial()</code></li> <li><code>partialmethod()</code></li> <li><code>reduce()</code></li> <li><code>wraps()</code></li> <li><code>lru_cache()</code></li> <li><code>cache()</code></li> <li><code>cached_property()</code></li> <li><code>total_ordering()</code></li> <li><code>singledispatch()</code></li> </ol> <h2 id="解释和用法">解释和用法</h2> <p>现在让我们开始进一步使用 functools 模块,并实际理解每个函数。</p> <h3 id="1部分">1.部分()</h3> <p><strong>partial</strong> 是以另一个函数为自变量的函数。它接受一组位置参数和关键字参数,这些输入被锁定在函数的参数中。</p> <p>然后 <strong>partial</strong> 返回所谓的 <em>partial 对象</em>,其行为类似于已经定义了那些参数的原始函数。</p> <p>它用于将多参数函数转换为单参数函数。它们可读性更强、更简单、更容易键入,并且提供了高效的代码补全。</p> <p>例如,我们将尝试找出 0-10 范围内的数字的平方,首先使用常规函数,然后使用 functools 的 partial()得到相同的结果。这将有助于我们理解它的用法。</p> <ul> <li>使用传统功能</li> </ul> <pre><code class="language-py">def squared(num): return pow(num, 2) print(list(map(squared, range(0, 10)))) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] </code></pre> <ul> <li>使用 functools 中的<code>partial()</code></li> </ul> <pre><code class="language-py">from functools import partial print(list(map(partial(pow, exp=2), range(0, 10)))) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] </code></pre> <h3 id="2partialmethod">2.partialmethod()</h3> <p>partialmethod 函数类似于 partial 函数,用作类方法的分部函数。它被设计成一个方法定义,而不是可直接调用的。简单地说,它是包含在我们自定义类中的方法。它可用于创建方便的方法,为该方法预定义一些设定值。让我们看一个使用这种方法的例子。</p> <pre><code class="language-py">from functools import partialmethod class Character: def __init__(self): self.has_magic = False @property def magic(self): return self.has_magic def set_magic(self, magic): self.has_magic = bool(magic) set_has_magic = partialmethod(set_magic, True) # Instantiating witcher = Character() # Check for Magical Powers print(witcher.magic) # False # Providing Magical Powers to our Witcher witcher.set_has_magic() print(witcher.magic) # True </code></pre> <h3 id="3减少">3.减少()</h3> <p>这种方法经常用于输出某种累计值,由某种预定义的函数计算。它将一个函数作为第一个参数,将一个 iterable 作为第二个参数。它还有一个初始值设定项,如果函数中没有指定初始值设定项的任何特定值,默认为 0,还有一个迭代器来遍历所提供的 iterable 的每一项。</p> <p><strong>附加内容:</strong><a href="https://www.askpython.com/python/reduce-function" target="_blank">Python 中的<code>reduce()</code>函数</a></p> <ul> <li>使用<code>reduce()</code></li> </ul> <pre><code class="language-py">from functools import reduce # acc - accumulated/initial value (default_initial_value = 0) # eachItem - update value from the iterable add_numbers = reduce(lambda acc, eachItem: acc + eachItem, [10, 20, 30]) print(add_numbers) # 60 </code></pre> <h3 id="4换行">4.换行()</h3> <p><strong>包装器</strong>接受它正在包装的函数,并在定义包装器函数时充当函数装饰器。它更新包装函数的属性以匹配被包装的函数。如果没有使用 <strong><code>wraps()</code></strong> 将此更新传递给包装器函数,则包装器函数的元数据将被返回,而不是原始函数的元数据或属性,它们应该是整个函数的实际元数据。为了避免这些类型的错误程序,包装()非常有用。</p> <p>还有一个相关的函数是 <strong><code>update_wrapper()</code></strong> 函数,与 wraps()相同。<em>wraps()函数是 update_wrapper()函数的语法糖,也是调用 update_wrapper()的方便函数。</em></p> <p>让我们看一个上面的例子来更好地理解这个函数。</p> <ul> <li>在不调用包装并尝试访问元数据的情况下定义装饰函数</li> </ul> <pre><code class="language-py">def my_decorator(func): def wrapper(*args, **kwargs): """ Wrapper Docstring """ return func(*args, **kwargs) return wrapper @my_decorator def original_func(): """ Original Function Doctstring """ return "Something" print(original_func()) print(original_func.__name__) print(original_func.__doc__) # Output ''' Something wrapper Wrapper Docstring ''' </code></pre> <ul> <li>定义相同的装饰函数,调用<code>wraps()</code>并尝试访问元数据</li> </ul> <pre><code class="language-py">from functools import wraps def my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): """ Wrapper Docstring """ return func(*args, **kwargs) return wrapper @my_decorator def original_func(): """ Original Function Doctstring """ return "Something" print(original_func()) print(original_func.__name__) print(original_func.__doc__) # Output """ Something original_func Original Function Doctstring """ </code></pre> <h3 id="5lru_cache-maxsize128--typedfalse-">5.lru_cache( <em>maxsize=128</em> , <em>typed=False</em> )</h3> <p>它是一个装饰器,用一个记忆化的可调用函数包装一个函数,这简单地意味着当相同的参数被用于那个非常特殊的昂贵函数时,它在执行昂贵的 I/O 函数操作的同时使函数调用变得高效。它实际上使用最近 maxsize 调用的缓存结果。 <strong>LRU</strong> 在 <strong>lru_cache()</strong> 中是 <strong>L</strong> 东 <strong>R</strong> 最近 <strong>U</strong> sed 的缩写。</p> <p>它有一个默认的 <em><strong>maxsize</strong></em> 为 128,它设置了最近调用的数量,这些调用将被缓存或保存,以便在以后的某个时间点用于相同的操作。 <strong>typed=False</strong> 将不同类型的函数参数值缓存在一起,简单来说,这意味着如果我们编写 <strong>type=True</strong> ,那么一个 <strong>integer 10</strong> 和一个 <strong>float 10.0</strong> 的缓存值将被分别缓存。</p> <p>lru_cache 函数还集成了其他三个函数来执行一些额外的操作,即</p> <ul> <li><strong>cache _ parameters()</strong>–它返回一个新的<strong>字典</strong>,显示 maxsize 和 typed 的值。这只是为了提供信息,数值突变不会影响它。</li> <li><strong>cache _ info()</strong>–用于测量缓存在需要时重新调优 maxsize 的效率。它输出一个命名元组,显示被包装函数的命中、未命中、最大大小和当前大小。</li> <li><strong>cache _ clear()</strong>–用于清除之前缓存的结果。</li> </ul> <p>在使用函数 <strong>lru_cache()</strong> 时,还有一些要点需要记住。</p> <ul> <li>由于使用 lru_cache()时结果的底层存储是一个字典,** args 和**kwargs 必须是可散列的。*</li> <li>因为只有当一个函数无论执行多少次都返回相同的结果时,缓存才起作用,所以它应该是一个在执行后不会产生副作用的纯函数。</li> </ul> <p>为了便于理解,我们将看到打印斐波那契数列的经典例子。我们知道,对于这个计算,迭代是使用相同的值一次又一次地完成的,以在找到 Fibonacci 数时输出该数。<em>嗯,缓存那些重复数字的值似乎是 <strong>lru_cache()</strong> 的一个很好的用例。</em>让我们看看它的代码。</p> <p><strong>代码:</strong></p> <pre><code class="language-py">from functools import lru_cache @lru_cache(maxsize=32) def fibonacci(n): if n < 2: return n print(f"Running fibonacci for {n}") return fibonacci(n - 1) + fibonacci(n - 2) print([fibonacci(n) for n in range(15)]) print(fibonacci.cache_parameters()) print(fibonacci.cache_info()) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Running fibonacci for 2 Running fibonacci for 3 Running fibonacci for 4 Running fibonacci for 5 Running fibonacci for 6 Running fibonacci for 7 Running fibonacci for 8 Running fibonacci for 9 Running fibonacci for 10 Running fibonacci for 11 Running fibonacci for 12 Running fibonacci for 13 Running fibonacci for 14 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] {'maxsize': 32, 'typed': False} CacheInfo(hits=26, misses=15, maxsize=32, currsize=15) </code></pre> <p><strong>说明</strong>:</p> <p>我们可以看到,对于 15 范围内的每个不同值,print 语句只提供了一次输出。虽然迭代已经做了很多,但是通过使用 <strong>lru_cache()</strong> ,我们只能看到唯一的结果被打印,重复的结果被缓存。在结果旁边是上述函数执行后的信息。</p> <h3 id="6缓存">6.缓存()</h3> <p>这个函数是 lru_cache()本身的一个较小的轻量级形式。但是缓存值的数量没有固定的界限。因此,我们不需要为它指定 maxsize。和使用 <strong>lru_cache(maxsize=None)是一样的。</strong></p> <p>因为使用这个函数不会忘记正在缓存的值,所以它使得 cache()比有大小限制的 lru_cache()快得多。这是 Python 3.9 的一个新的补充</p> <p>使用此函数时要记住的一件事是,在使用大量输入的函数实现它时,我们可能会得到非常大的缓存大小。因此,应该谨慎使用,并事先考虑清楚。</p> <h3 id="7cached-_-property">7.cached _ property()</h3> <p><strong>cached_property()</strong> 类似于 Python 中的 <strong>property()</strong> ,允许我们将类属性作为内置函数转换为属性或托管属性。<em>它额外提供了<strong>缓存功能</strong></em> 并在 <strong>Python 3.8</strong> 中引入</p> <p>计算值计算一次,然后保存为该实例生命周期的普通属性。与 property()函数不同,cache_property()还允许在没有定义 setter 的情况下进行写入。</p> <p>Cached_property 仅运行:</p> <ul> <li>如果属性还不存在</li> <li>如果它必须执行查找</li> </ul> <p>通常,如果该属性已经存在于函数中,它会像普通属性一样执行读写操作。为了清除缓存的值,需要删除属性,这实际上允许再次调用 cached_property()函数。</p> <ul> <li>不使用 catched_property(),查看输出</li> </ul> <pre><code class="language-py">class Calculator: def __init__(self, *args): self.args = args @property def addition(self): print("Getting added result") return sum(self.args) @property def average(self): print("Getting average") return (self.addition) / len(self.args) my_instance = Calculator(10, 20, 30, 40, 50) print(my_instance.addition) print(my_instance.average) """ Output Getting added result 150 Getting average Getting added result 30.0 """ </code></pre> <ul> <li>使用 catched_property(),查看输出</li> </ul> <pre><code class="language-py">from functools import cached_property class Calculator: def __init__(self, *args): self.args = args @cached_property def addition(self): print("Getting added result") return sum(self.args) @property def average(self): print("Getting average") return (self.addition) / len(self.args) my_instance = Calculator(10, 20, 30, 40, 50) print(my_instance.addition) print(my_instance.average) """ Output Getting added result 150 Getting average 30.0 """ </code></pre> <p><strong>说明:</strong></p> <p>我们可以看到,在计算平均值时,得到相加结果的<strong>已经打印了两次*,因为对于第一个函数,它的结果还没有被缓存。但是当我们使用</strong>@ cached _ property decorator<strong>时,加法的结果已经被缓存,因此直接从内存中使用来获得平均值。</strong>*</p> <h3 id="8total_ordering"><em><strong>8.total_ordering()</strong></em></h3> <p><em><strong>functools 中的这个高阶函数,当用作类装饰器时,假设我们的类包含一个或多个丰富的比较排序方法,它提供了其余的方法,而没有在我们的类中显式定义。</strong></em></p> <p><em><em><em>这意味着当我们在我们的类中使用比较 dunder/magic 方法 <code>**__gt__()**, **__lt__(), __ge__(), __le__()**</code>时,如果我们使用 define <strong><code>__eq__()</code></strong> 和</em>只是其他四个方法</em>中的一个,其余的将由 functools 模块中的 <strong><code>total_ordering()</code></strong> 自动定义。</em>**</p> <p><em><strong>需要注意的一件重要事情是,它确实降低了代码执行的速度,并且为我们的类中没有明确定义的比较方法创建了更复杂的堆栈跟踪。</strong></em></p> <p><em><strong>让我们看一个简单的例子。</strong></em></p> <p><em><strong><strong>代码:</strong></strong></em></p> <pre><code class="language-py">*@functools.total_ordering class Student: def __init__(self, name, marks): self.name = name self.marks = marks def __eq__(self, other): return self.marks == other.marks def __gt__(self, other): return self.marks > other.marks student_one = Student("John", 50) student_two = Student("Peter", 70) print(student_one == student_two) print(student_one > student_two) print(student_one >= student_two) print(student_one < student_two) print(student_one <= student_two) """ Output: False False False True True """* </code></pre> <p><em><strong><strong>说明:</strong></strong></em></p> <p><em><strong><em>在上面的代码中,我们用不同的语法导入了</em> <strong><code>total_ordering()</code></strong> <em>。这与从前面所有示例中使用的 functools 导入是一样的。</em></strong></em></p> <p><em><strong>我们创建的类只包含两个比较方法。但是通过使用 total_ordering() class decorator,我们使我们的类实例能够自己派生其余的比较方法。</strong></em></p> <h3 id="9单一调度"><em><strong>9.</strong>单一调度</em><em>()</em>**</h3> <p><em><strong>当我们定义一个函数时,它对不同输入类型的参数执行相同的操作。但是,如果我们希望一个函数在参数的输入类型不同时有不同的行为呢?</strong></em></p> <p><em><strong>我们发送一个列表或一个字符串或一些其他类型,我们想要不同的输出取决于我们发送的数据。如何才能实现这一点?</strong></em></p> <p><em><strong>functools 模块有 <strong><code>singledispatch()</code></strong> 装饰器,帮助我们编写这样的函数。实现基于被传递的参数的类型。</strong></em></p> <p><em><strong>泛型函数的 <strong><code>register()</code></strong> 属性和 <code>**singledispatch()**</code>方法用于修饰重载的实现。如果实现像静态类型语言一样用类型注释,装饰器会自动推断传递的参数的类型,否则类型本身就是装饰器的参数。</strong></em></p> <p><em><strong>同样,它可以通过使用 <strong><code>singledispatchmethod()</code></strong> 实现为类方法,以达到相同的结果。</strong></em></p> <p><em><strong>让我们看一个例子来更好地理解它。</strong></em></p> <pre><code class="language-py">*from functools import singledispatch @singledispatch def default_function(args): return f"Default function arguments: {args}" @default_function.register def _(args: int) -> int: return f"Passed arg is an integer: {args}" @default_function.register def _(args: str) -> str: return f"Passed arg is a string: {args}" @default_function.register def _(args: dict) -> dict: return f"Passed arg is a dict: {args}" print(default_function(55)) print(default_function("hello there")) print(default_function({"name": "John", "age": 30})) print(default_function([1, 3, 4, 5, 6])) print(default_function(("apple", "orange"))) """ Output: Passed arg is an integer: 55 Passed arg is a string: hello there Passed arg is a dict: {'name': 'John', 'age': 30} Default function arguments: [1, 3, 4, 5, 6] Default function arguments: ('apple', 'orange') """* </code></pre> <p><em><strong><strong>说明:</strong></strong></em></p> <p><em><strong>在上面的例子中,我们可以看到函数实现是基于传递的参数类型完成的。与其他类型不同,未定义的类型由默认函数执行。</strong></em></p> <h2 id="结论-9"><em><strong>结论</strong></em></h2> <p><em><strong>在本文中,我们介绍了 Python 中 functools 模块提供的大多数函数。这些高阶函数提供了一些很好的方法来优化我们的代码,从而产生干净、高效、易于维护和读者友好的程序。</strong></em></p> <h2 id="参考"><em><strong>参考</strong></em></h2> <p><em><strong><a href="https://docs.python.org/3/library/functools.html" target="_blank">Python functools 文档</a></strong></em></p> <h1 id="gamestop-和个人数据共享">gamestop 和个人数据共享</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/gamstop-and-personal-data-sharing" target="_blank">https://www.askpython.com/python/gamstop-and-personal-data-sharing</a></p> </blockquote> <p>GamStop 于 2018 年由英国赌丨博委员会(UKGC)根据国家在线自我排除计划(NOSES)成立,是一个自我排除计划,旨在通过阻止用户访问这些赌丨博网站和应用程序来禁止用户使用赌丨博应用程序和网站。该计划最初是一项福利服务,旨在帮助赌丨博成瘾的人从强迫性赌丨博中康复,并防止人们成为强迫性赌徒。</p> <p>GamStop 需要用户的个人信息进行注册,包括身份证明、地址和工作证明以及联系信息。许多用户不愿向 GamStop 提供他们的个人信息,因为他们害怕自己的个人信息被泄露。老实说,一些英国玩家更喜欢不在 GamStop 上的赌场,那里没有数据泄露的机会。因此,用户需要关于谁可以访问他们的个人信息的数据。这里的列表给出了谁可以访问 GamStop 中的数据的完整说明。</p> <h2 id="服务提供商">服务提供商</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/27bef769fa33f938aa67cd905e5609c5.png" alt="Service Providers" loading="lazy"></p> <p>GamStop 与多家服务提供商合作,这些服务提供商通过其<a href="https://www.askpython.com/python-modules/gui-applications-using-python-qt" target="_blank">应用</a>为用户提供最佳资源。因此,他们需要获取用户的个人信息。需要用户个人信息的 GamStop 服务提供商列表如下:</p> <ul> <li>数据仓库(他们处理 IT、开发和软件交付服务)</li> <li>SendInBlue(电子邮件服务提供商)</li> <li>AWS(云服务提供商)</li> <li>跨联盟(验证用户身份的提供商)</li> <li>Onfido(验证用户身份的提供商)</li> <li>Fetchify(查找用户地址的提供者)</li> <li>连接辅助(消费者服务提供商)</li> <li>Zendesk(案例管理服务提供商)</li> <li>微软(软件提供商)</li> <li>Nexus IT (IT 支持提供商)</li> <li>Citrix(调查安全问题和共享敏感信息)</li> </ul> <h2 id="赌丨博经营者">赌丨博经营者</h2> <p>这些数据也透露给赌丨博经营者。GamStop 允许赌丨博运营商获取信息,以验证可能试图使用赌丨博网站的用户的身份。赌丨博运营商检查是否有人注册了 GamStop 试图进入网上赌场。赌丨博运营商还检查是否有任何玩家在 7 年内已经在 GamStop 注册,并将此详细信息提供给 GamStop。</p> <p>根据 GamStop 使用条款,如果用户已经达到自行退出期限的末尾,并且他们希望在完成期限后停用该方案,赌丨博运营商将能够匹配该用户使用 Gamstop,从停用起持续 7 年。用户如有任何疑问,也可与赌丨博经营者联系。</p> <h2 id="赌丨博佣金">赌丨博佣金</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5711e9760f85f635e51bafc773802fde.png" alt="Ukgc" loading="lazy"></p> <p>由于 GamStop 是由 UKGC 为了福利和意识而建立的,如果他们有义务这样做,赌丨博委员会可以从 GamStop 那里要求个人信息。他们需要细节,以确保该计划的顺利运作和维持规则。这也让赌丨博委员会对 GamStop 的功能有了一个概念。</p> <h2 id="研究">研究</h2> <p>一些案例用于研究中的案例分析,用户的详细信息可能需要进一步研究。在这种情况下,在披露用户的个人信息之前,需要征得用户的特别许可和明确同意。</p> <h2 id="gamcare">Gamcare</h2> <p>Gamcare 是另一个提高认识的计划,它管理着全国赌丨博帮助热线,为嗜赌成性的赌徒及其家庭提供支持。与用户相关的数据只有在用户明确同意的情况下才能被披露。</p> <h2 id="法律权利和义务">法律权利和义务</h2> <p>法律、政府机构或法院命令可能会要求 GamStop 报告与用户相关的信息。这种披露可能是强制性的,以便在法律主张辩护的基础上提供某种理由。</p> <h2 id="公司重组">公司重组</h2> <p>如果 <a href="https://www.linuxfordevices.com/news/gamstop-self-exclusion-tool-why-do-players-need-it" target="_blank">GamStop 工具</a>遇到重组或出售的情况,他们将被要求向新的组织者、挪用者及其指导者透露 GamStop 数据。GamStop 只同意在严格保密和信任的基础上透露细节。GamStop 非常重视用户的隐私,并忠实地维护他们的隐私政策,因此如果他们不得不将详细信息交给这些收购者,他们将选择法律保护,以保持保护帐户信息的承诺,并遵守他们的隐私政策规则。</p> <h2 id="其他人">其他人</h2> <p>持牌赌丨博运营商可能位于英国和欧洲经济区(EEA)以外。在这种情况下,GamStop 可能会将用户的个人信息传输给这些海外运营商,以获得受合同条款保护的服务。</p> <h2 id="结论-10">结论</h2> <p>Gamstop 是一项自我排除服务,已帮助成千上万的人从赌丨博成瘾和因赌丨博成瘾而产生的财务和精神消耗中康复。除此之外,GamStop 通过限制网站和应用程序的过度使用,帮助防止了不安全赌丨博习惯的发展。Gamstop 还保持着非常严格的隐私政策,禁止侵犯用户的隐私。除了为维护服务而必须披露信息之外,GamStop 还坚信根据用户政策保护用户的敏感信息。</p> <h1 id="gamstop-api值得等待开放使用">GamStop API:值得等待开放使用</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/gamstop-api-worth-the-wait-for-open-use" target="_blank">https://www.askpython.com/python/gamstop-api-worth-the-wait-for-open-use</a></p> </blockquote> <p>软件平台的力量在于它能够准确地交付开发者和最终用户想要的东西。特别是应用编程接口(API)通常使这种情况成为可能,因为它为一个软件平台与另一个软件平台通信打开了大门。在<a href="https://www.askpython.com/python/web-technologies-frontend-online-casinos" target="_blank">在线赌场赌丨博社区</a>中,软件平台之间的交叉通信尤其令人感兴趣。</p> <h2 id="在线赌场软件开发商如何使用-api">在线赌场软件开发商如何使用 API</h2> <p>在网上赌场赌丨博的早期,网上赌场平台的运作方式非常粗糙。几乎没有任何跨应用程序的集成,因为没有任何软件开发工具可以创建连接点。相反,赌场软件开发商局限于建立一个“独立”的平台和赌场游戏,只能在这个平台上运行。</p> <p>大约十年前发生的变化是新的软件开发工具出现了。其中一些软件开发工具打开了软件平台之间更多集成的大门,在线赌场社区很快就扑了上来。</p> <p>想象一下,在 2010 年之前,你拥有一个在线赌场网站。作为所有者,你必须决定你是否想要一个来自软件开发商如 Microgaming、Netent 或 Playtech 的全包软件程序。记住,你只能选择一个。你不能做的是创建一个在线赌场环境,在同一个在线赌场内提供来自任何和所有顶级赌场游戏软件开发商的赌场游戏。</p> <p>由于近年来 HTML5 和 API 等协议的引入,您可以准确地构建您想要的在线赌场环境。您可以创建一个基本的赌场平台,允许您整合来自世界各地的软件开发商的游戏。你可以感谢 API 的出现,因为赌场老板拥有这种灵活性。您还可以集成支持软件程序,如 GamStop Self-exclusion 程序。</p> <h2 id="什么是-gamstop为什么它与在线赌场社区相关">什么是 GamStop,为什么它与在线赌场社区相关?</h2> <p>当英国赌丨博委员会越来越担心英国赌丨博问题激增时,他们知道他们需要解决这个问题。在他们看来,解决赌丨博问题的唯一方法是为在线赌丨博者创造一种自助的方式。他们选择这种方式是因为你不能要求自由社会中的人们照顾自己。</p> <p>UKGC 给出的答案是 GamStop 自我排除计划。他们帮助创建了这个程序,作为问题赌徒从他们赌丨博的实际在线赌丨博运营商那里获得帮助的一种手段。GamStop 的工作方式如下。</p> <p>一名英国在线赌徒决定努力控制他们的在线赌丨博。知道他们最喜欢的英国在线赌丨博运营商需要订阅 GamStop 计划,他们在他们最喜欢的赌丨博网站上找到了 GamStop 链接。通过这个链接,他们可以自愿注册加入 GamStop 数据库。一旦他们进入数据库,他们知道所有许可的英国在线赌丨博网站将禁止他们尝试赌丨博。注:豁免期由参赌者在注册时决定。</p> <p>所有这些都是由 GamStop 的 API 促成的。GamStop 协议允许所有订购的赌场运营商集成并访问 GamStop 数据库。利用注册赌徒提供的关键信息,他们能够识别这些赌徒访问英国赌丨博网站的企图。</p> <p>这很好地展示了 API 如何帮助整个软件平台社区相互交流。它展示了作为一种开放使用资源的可能性。</p> <h2 id="gamstop-的局限性">GamStop 的局限性</h2> <p>虽然 GamStop 的 API 使得不相关的在线赌丨博运营商之间的通信成为可能,但 GamStop 程序也有其局限性。关键的限制是,它只与英国政府许可的在线赌丨博运营商和 GamStop 的订阅会员有关。这就给 GamStop 的赌徒们留下了其他在线赌丨博的选择,他们希望避开 GamStop 的自我禁止期。</p> <p>其中一个方法是<a href="https://www.nongamstopwager.com/casinos-not-on-gamstop/" target="_blank">访问没有被 GamStop</a> 屏蔽的英国在线赌场。这并不是一件困难的事情,因为如果一个积极的在线赌徒知道去哪里找,这样的赌丨博网站是很多的。</p> <p>GamStop 的 API 可以用来关闭一些其他的赌丨博入口吗?是啊!它只需要这些其他选项的促进者愿意与 GamStop 方案合作。GamStop 的扩展正是让 GamStop 的 API 值得等待的原因。</p> <p>最重要的问题是什么?在线赌丨博提供商希望尽可能多的业务。如果没有一个像 UKGC 这样的管理机构授权他们参与 GamStop,那么整合到这个项目中的动机就不存在了。但是…关于 GamStop 的 API 在未来的扩展,似乎有很大的可能性。</p> <h1 id="python-中的垃圾收集">Python 中的垃圾收集</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/garbage-collection-in-python" target="_blank">https://www.askpython.com/python-modules/garbage-collection-in-python</a></p> </blockquote> <p>在本文中,我将向您介绍 Python 中垃圾收集的概念。垃圾收集是 Python 自动管理其内存的一种方式。</p> <p>它是通过使用参考计数器来实现的。所以在我们进入垃圾收集的概念之前,让我们先了解一下什么是引用计数器。</p> <h2 id="python-中的引用计数器是什么">Python 中的引用计数器是什么?</h2> <p>引用计数器是在运行的程序中对对象的引用次数。它允许 Python 编译器知道什么时候使用了一个<a href="https://www.askpython.com/python/python-variables" target="_blank">变量</a>,什么时候从内存中移除一个对象是安全的。</p> <p>这减少了程序员跟踪填充系统资源的对象的工作,并允许他们专注于创建程序。</p> <h2 id="python-中的垃圾收集是如何工作的">Python 中的垃圾收集是如何工作的?</h2> <p>让我们理解 Python 如何使用引用计数器在后端执行垃圾收集。我们可以用一个简单的例子来理解这一点。</p> <p>我们将首先介绍引用是如何计数的,然后看看 Python 如何识别对象没有引用的情况。</p> <p>看看下面的代码:</p> <pre><code class="language-py"># Increasing reference count as more variables link to it reference1 = 9 # Reference count for the value 9, becomes 1 reference2 = reference1 # Reference count for value 9 becomes 2 reference3 = reference1 # Reference count for value 9 becomes 3 # Decreasing reference count as the variable values change reference2 = 10 # Reference count for value 9 decreases to 2 reference3 = 5 # Reference count for value 9 decreases to 1 reference1 = 1 # Reference count for value 9 decreases to 0 # After the reference value becomes 0, the object is deleted from memory </code></pre> <p>从上面可以清楚地看到,一旦最后一个引用变量“reference1”的值更改为 1,值 9 在内存中就不再有引用了。</p> <p>一旦 Python 解释器在整个代码中没有发现对某个值的引用,垃圾收集器就会将内存释放给该值以释放空间。</p> <h2 id="什么是参考周期">什么是参考周期?</h2> <p>让我们看看另一个概念,称为参考循环。在这里,我们只是简单地引用一个对象本身。看看下面的示例代码:</p> <pre><code class="language-py">>>> a = [] >>> a.append(a) >>> print a [[...]] </code></pre> <p>此外,我们将执行 a=[],并创建一个空列表。<code>a.append()</code>意味着我们将向列表中添加一些东西。</p> <p>在这种情况下:a .所以我们要向这个对象添加另一个空列表。这是怎么回事?</p> <p>如果我们调用<code>a</code>会看到这里有两个列表。</p> <p>所以我们已经创建了一个空列表,然后我们把这个列表附加到对象本身。所以在这个对象中,我们得到了一个列表,然后在这个对象中,这个列表被再次调用,所以引用计数器上升到 1。</p> <p>但是我们不再使用<code>a</code>,我们的程序不再调用它,但是引用计数器是 1。</p> <p>Python 有一种移除引用循环的方法,但它不会立即这么做。在引用了很多次之后,它会引用一些东西,然后不引用一些东西,这就是一个事件。</p> <p>所以在这种情况下,在多次出现之后,python 将运行它的垃圾收集,它将进入内存并查看每个对象。</p> <p>当它进入内存并查看每个对象时,它会看到这个对象在引用自己,我们的程序不再调用它,但它的引用计数为 1,但没有任何对象调用它。</p> <p>因此,它将继续删除它。</p> <h2 id="我们如何知道垃圾收集何时运行">我们如何知道垃圾收集何时运行?</h2> <p>嗯,我们可以通过使用一个名为<code>garbage collection</code>的 Python 模块来看这个问题。我们将通过导入 gc 来导入垃圾收集模块。</p> <p>然后,我们获得阈值,以了解垃圾收集将在何时进行,并捕获这些引用周期。</p> <p>我们可以通过键入 gc.get_threshold()来获取这些信息。</p> <pre><code class="language-py">import gc gc.get_threshold() </code></pre> <p>上面两行代码显示了下面的输出。</p> <pre><code class="language-py">(700,10,10) </code></pre> <p>让我们仔细看看输出。值“700”的意思是,在引用某个对象 700 次后,Python 将继续收集引用周期。</p> <p>简单来说,在出现 700 次后,Python 将运行一个脚本或算法,遍历并清理你的内存。</p> <p>虽然当引用计数器由于引用周期而停留在 1 时,Python 会在引用计数器达到 0 时自动执行此操作。那么只有在 700 次之后,Python 才会运行垃圾收集来捕捉这些循环。</p> <h2 id="手动使用垃圾收集">手动使用垃圾收集</h2> <p>我们可以通过使用模块来改变这一点。我们不会在本文中详细讨论这个问题,但是请注意您可以更改它。</p> <p>相同的代码如下所示。</p> <p>用户也可以打开或关闭垃圾收集。使用该模块,您可以做很多事情。</p> <pre><code class="language-py">import gc gc.disable() class Track: def __init__(self): print("Intitialisting your object here") def __del__(self): print("Deleting and clearing memory") print("A") A = Track() print("B") B = Track() print("deleting here...") del A del B gc.collect() </code></pre> <p>为了解释上面的代码,简而言之,我已经导入了垃圾收集器模块,但是在代码的开头使用<code>gc.disable()</code>禁用了垃圾收集。</p> <p>这是为了确保不进行自动垃圾收集。然后,用一个构造函数和析构函数定义一个类轨迹。两个对象被定义为 A 和 B,它们在定义后在控制台中打印<code>Initialising your object here</code>。</p> <p>然后使用<code>del</code>方法删除对象,并在成功删除对象后在控制台中打印<code>Deleting and clearing memory</code>。</p> <p><code>gc.collect()</code>方法确保垃圾收集器释放对象 A 和 b 占用的内存空间。</p> <p>所以当我们到了那里,你会看到我们能用它做多少事。但是现在,只需要知道 python 在维护和管理我们的内存方面做得非常好。</p> <h2 id="如果没有进行垃圾收集原因可能是什么">如果没有进行垃圾收集,原因可能是什么?</h2> <p>我想指出的另一件事是,如果你的内存快满了并且用完了,垃圾收集将不会运行,因为垃圾收集运行需要内存。</p> <p>假设你的程序很大,占用了很多内存,没有足够的内存来运行垃圾收集,那么你会得到一堆异常,你会有一堆问题。</p> <p>所以要注意,如果你有很多这样的问题,那么你可能要习惯这个模块,在你的程序中早一点运行它。</p> <h2 id="结论-11">结论</h2> <p>希望这篇文章有深刻的见解。请在下面的反馈部分告诉我们您的想法。</p> <h2 id="参考-1">参考</h2> <p><a href="https://docs.python.org/3/library/gc.html" target="_blank">https://docs.python.org/3/library/gc.html</a></p> <h1 id="python-中如何生成平衡括号">Python 中如何生成平衡括号?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/generate-balanced-brackets" target="_blank">https://www.askpython.com/python/examples/generate-balanced-brackets</a></p> </blockquote> <p>在本教程中,我们将了解一个非常有趣的问题,称为<strong>生成平衡括号</strong>。平衡括号意味着左括号和右括号的数量完全相等。</p> <hr> <h2 id="理解生成平衡括号的概念">理解生成平衡括号的概念</h2> <p>我们将处理许多变量,即 n 的值(由用户给定)、输出字符串、开括号和闭括号的计数以及迭代器。</p> <p>在每个递归调用中,输出字符串将通过插入左括号或右括号来操作。并据此增加开括号和闭括号的计数,递归调用函数。</p> <p>我们不断检查每个递归调用中括号的平衡。</p> <p><em><strong>了解更多关于递归的知识:<a href="https://www.askpython.com/python/python-recursion-function" target="_blank">Python 中的递归</a></strong></em></p> <hr> <h2 id="在-python-中生成平衡括号">在 Python 中生成平衡括号</h2> <pre><code class="language-py">def all_balanced(n,output,itr,count_open,count_close): # base case if(itr == 2*n): print(output) return # Insert open curly bracket if(count_open<n): output = output[:itr] + '{' + output[itr+1:] all_balanced(n,output,itr+1,count_open+1,count_close) # Insert closing curly brackwt if(count_open>count_close): output = output[:itr] + '}' + output[itr+1:] all_balanced(n,output,itr+1,count_open,count_close+1) return n= int(input()) all_balanced(n,"",0,0,0) </code></pre> <hr> <h2 id="抽样输出">抽样输出</h2> <p>下面的输出是当 n 的值等于 4 时的结果。这意味着将有 4 个左括号和 4 个右括号。</p> <pre><code class="language-py">{{{{}}}} {{{}{}}} {{{}}{}} {{{}}}{} {{}{{}}} {{}{}{}} {{}{}}{} {{}}{{}} {{}}{}{} {}{{{}}} {}{{}{}} {}{{}}{} {}{}{{}} </code></pre> <hr> <p>我希望你清楚平衡括号问题的概念、问题和代码实现。</p> <p>感谢您的阅读!快乐学习!🙂</p> <hr> <h1 id="在-python-中生成随机颜色的方法">在 Python 中生成随机颜色的方法</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/generate-random-colors" target="_blank">https://www.askpython.com/python/examples/generate-random-colors</a></p> </blockquote> <p>嘿伙计们!在本教程中,我们将看看如何在 Python 中生成随机颜色。我们将创建两种不同形式的颜色。像 <a href="https://www.askpython.com/python/examples/nan-in-numpy-and-pandas" target="_blank">Numpy</a> 、 <a href="https://www.askpython.com/python-modules/matplotlib/python-matplotlib" target="_blank">Matplotlib</a> 、 <a href="https://www.askpython.com/python-modules/python-turtle" target="_blank">turtle</a> 这样的 Python 模块都可以用来产生颜色。</p> <hr> <h2 id="使用-random函数生成随机颜色">使用 random()函数生成随机颜色</h2> <pre><code class="language-py">import random for i in range(3): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) rgb = [r,g,b] print('A Random color is :',rgb) </code></pre> <p>首先,在 Python 中导入 random 函数来获得随机颜色。变量 r 代表红色,g 代表绿色,b 代表蓝色。我们已经知道 RGB 格式包含一个从 0 到 255 的整数值。</p> <p>因此,我们将范围设置为 0 到 255。它将使用范围内的任何值。 <strong>random.randint()</strong> 是确定范围的方法。</p> <pre><code class="language-py">A Random color is : [222, 169, 158] A Random color is : [66, 19, 84] A Random color is : [157, 146, 62] </code></pre> <hr> <h2 id="使用-numpy-模块生成随机颜色">使用 Numpy 模块生成随机颜色</h2> <pre><code class="language-py">import numpy as np for i in range(3): random_color=list(np.random.choice(range(255),size=3)) print("A Random color is: ",random_color) </code></pre> <p>然后在可变随机颜色中为颜色指定一个值和大小。因为我们是以列表的形式开始的,所以颜色会出现在列表中—接下来,打印随机颜色。</p> <pre><code class="language-py">A Random color is: [241, 4, 161] A Random color is: [96, 48, 224] A Random color is: [228, 20, 55] </code></pre> <hr> <h2 id="使用-matplotlib-库生成随机颜色">使用 Matplotlib 库生成随机颜色</h2> <pre><code class="language-py">import matplotlib.pyplot as plt import random no_of_colors=5 color=["#"+''.join([random.choice('0123456789ABCDEF') for i in range(6)]) for j in range(no_of_colors)] print(color) for j in range(no_of_colors): plt.scatter(random.randint(0,10),random.randint(0,10),c=color[j],s=200) plt.show() </code></pre> <p>在名为“颜色数量”的变量中,指定一个值。然后使用 join()方法将#和颜色代码连接起来。颜色代码总是以#开头。若要迭代,请将用于循环。颜色代码现已生成。</p> <p>因为我们是以列表的形式开始的,所以颜色会出现在列表中—接下来,打印随机颜色。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/29aafde2458c29815127fd82b789aa3d.png" alt="Random Colors Using Matplotlib Output" loading="lazy"></p> <p>Random Colors Using Matplotlib Output</p> <hr> <h2 id="结论-12">结论</h2> <p>恭喜你!您刚刚学习了如何以不同的方式生成随机颜色。希望你喜欢它!😇</p> <p>喜欢这个教程吗?无论如何,我建议你看一下下面提到的教程:</p> <ol> <li><a href="https://www.askpython.com/python/visualizing-colors-in-images" target="_blank">使用直方图可视化图像中的颜色–Python OpenCV</a></li> <li><a href="https://www.askpython.com/python-modules/colorsys-module" target="_blank">Python colorsys 模块</a></li> </ol> <p>感谢您抽出时间!希望你学到了新的东西!!😄</p> <h1 id="如何在-python-中生成随机字符串">如何在 Python 中生成随机字符串</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/generate-random-strings-in-python" target="_blank">https://www.askpython.com/python/examples/generate-random-strings-in-python</a></p> </blockquote> <p>在本文中,我们将看看如何在 Python 中生成随机字符串。顾名思义,我们需要生成一个随机的字符序列,它适用于<code>random</code>模块。</p> <p>这里有各种方法,所以我们将从最直观的方法开始;使用随机整数。</p> <hr> <h2 id="从随机整数序列构建一个字符串">从随机整数序列构建一个字符串</h2> <p>如您所知,<code>chr(integer)</code>将整数映射到字符,假设它在 ASCII 限制内。(本文中取为<code>255</code>)</p> <p>我们可以使用这个映射将任意整数缩放到 ASCII 字符级别,使用<code>chr(x)</code>,其中<code>x</code>是随机生成的。</p> <pre><code class="language-py">import random # The limit for the extended ASCII Character set MAX_LIMIT = 255 random_string = '' for _ in range(10): random_integer = random.randint(0, MAX_LIMIT) # Keep appending random characters using chr(x) random_string += (chr(random_integer)) print(random_string, len(random_string)) </code></pre> <p><strong>样本输出</strong></p> <pre><code class="language-py">ð|ÒR: Rè 10 </code></pre> <p>这里,虽然字符串的长度似乎是 10 个字符,但是我们会看到一些奇怪的字符以及换行符、空格等。</p> <p>这是因为我们考虑了整个 ASCII 字符集。</p> <p>如果我们只想处理英文字母,我们可以使用它们的 ASCII 值。</p> <pre><code class="language-py">import random random_string = '' for _ in range(10): # Considering only upper and lowercase letters random_integer = random.randint(97, 97 + 26 - 1) flip_bit = random.randint(0, 1) # Convert to lowercase if the flip bit is on random_integer = random_integer - 32 if flip_bit == 1 else random_integer # Keep appending random characters using chr(x) random_string += (chr(random_integer)) print(random_string, len(random_string)) </code></pre> <p><strong>样本输出</strong></p> <pre><code class="language-py">wxnhvYDuKm 10 </code></pre> <p>如你所见,现在我们只有大写和小写字母。</p> <p>但是我们可以避免所有这些麻烦,让 Python 为我们做这些工作。Python 为此给了我们<code>string</code>模块!</p> <p>让我们看看如何使用几行代码就能做到这一点!</p> <h2 id="使用字符串模块在-python-中生成随机字符串">使用字符串模块在 Python 中生成随机字符串</h2> <p>这里定义了 <a href="https://www.askpython.com/python/string/python-string-functions" target="_blank">Python 字符串</a>使用的字符列表,我们可以在这些字符组中挑选。</p> <p>然后我们将使用<code>random.choice()</code>方法随机选择字符,而不是像以前那样使用整数。</p> <p>让我们定义一个函数<code>random_string_generator()</code>,它为我们做所有这些工作。这将生成一个随机字符串,给定字符串的长度,以及允许从中采样的字符集。</p> <pre><code class="language-py">import random import string def random_string_generator(str_size, allowed_chars): return ''.join(random.choice(allowed_chars) for x in range(str_size)) chars = string.ascii_letters + string.punctuation size = 12 print(chars) print('Random String of length 12 =', random_string_generator(size, chars)) </code></pre> <p>这里,我们将允许的字符列表指定为<code>string.ascii_letters</code>(大写和小写字母),以及<code>string.punctuation</code>(所有标点符号)。</p> <p>现在,我们的主函数只有 2 行,我们可以使用<code>random.choice(set)</code>随机选择一个字符。</p> <p><strong>样本输出</strong></p> <pre><code class="language-py">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~ Random String of length 12 = d[$Om{;#cjue </code></pre> <p>我们确实生成了一个随机字符串,并且<code>string</code>模块允许在字符集之间进行简单的操作!</p> <h3 id="使随机生成更加安全">使随机生成更加安全</h3> <p>虽然上面的随机生成方法是可行的,但是如果你想让你的函数在加密上更加安全,那么使用<code>random.SystemRandom()</code>函数。</p> <p>随机生成器函数示例如下所示:</p> <pre><code class="language-py">import random import string output_string = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) print(output_string) </code></pre> <p><strong>输出</strong></p> <pre><code class="language-py">iNsuInwmS8 </code></pre> <p>这确保了您的字符串生成在加密方面是安全的。</p> <hr> <h2 id="随机-uuid-生成">随机 UUID 生成</h2> <p>如果你想生成一个随机的 <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" target="_blank">UUID</a> 字符串,<code>uuid</code>模块对这个目的很有帮助。</p> <pre><code class="language-py">import uuid # Generate a random UUID print('Generated a random UUID from uuid1():', uuid.uuid1()) print('Generated a random UUID from uuid4():', uuid.uuid4()) </code></pre> <p><strong>样本输出</strong></p> <pre><code class="language-py">Generated a random UUID from uuid1(): af5d2f80-6470-11ea-b6cd-a73d7e4e7bfe Generated a random UUID from uuid4(): 5d365f9b-14c1-49e7-ad64-328b61c0d8a7 </code></pre> <hr> <h2 id="结论-13">结论</h2> <p>在本文中,我们学习了如何在<code>random</code>和<code>string</code>模块的帮助下,在 Python 中生成随机字符串。</p> <h2 id="参考-2">参考</h2> <ul> <li>关于生成随机字符串的 JournalDev 文章</li> <li><a href="https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits" target="_blank">关于随机字符串生成的 StackOverflow 问题</a></li> </ul> <hr> <h1 id="gensim-word-2-vec完整指南">gensim word 2 vec–完整指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/gensim-word2vec" target="_blank">https://www.askpython.com/python-modules/gensim-word2vec</a></p> </blockquote> <p>Word2Vec 是一种算法,它将单词转换为向量,从而将相似的单词分组到向量空间中。它广泛应用于许多领域,如文档检索、机器翻译系统、自动补全和预测等。在本教程中,我们将学习如何使用 Gensim 库训练 Word2Vec 模型,以及加载将单词转换为向量的预训练。</p> <h2 id="word2vec">Word2Vec</h2> <p>Word2Vec 是谷歌设计的一种算法,它使用神经网络来创建单词嵌入,使得具有相似词义的嵌入往往指向相似的方向。例如,在向量空间中,像爱、关心等词的嵌入与像打架、战斗等词的嵌入相比,将指向相似的方向。这种模型还可以检测给定单词的同义词,并为部分句子建议一些附加单词。</p> <h2 id="gensim-word2vec">Gensim Word2Vec</h2> <p>Gensim 是一个开源的 Python 库,可用于主题建模、文档索引以及消除与大型语料库的相似性。Gensim 的算法相对于语料库的大小是独立于内存的。它也被设计用来扩展其他向量空间算法。</p> <p>Gensim 在<code>Word2Vec</code>类中提供了 Word2Vec 算法的实现以及其他一些自然语言处理的功能。让我们看看如何使用 Gensim 创建 Word2Vec 模型。</p> <h3 id="使用-gensim-开发一个-word2vec-模型">使用 Gensim 开发一个 Word2Vec 模型</h3> <p>Gensim Word2Vec 类采用的一些有用参数:</p> <ul> <li>句子:它是模型被训练来创建单词嵌入的数据。在大型语料库的情况下,它可以是标记/单词列表的列表,或者来自网络/磁盘的数据流。在我们的例子中,我们将使用出现在<a href="https://www.askpython.com/python-modules/tokenization-in-python-using-nltk" target="_blank"></a><strong>中的棕色语料库。</strong></li> <li><strong>size:它表示对于词汇表中的每个单词,您希望向量的维数是多长。其默认值为 100。</strong></li> <li><strong>窗口:当前单词与其相邻单词之间的最大距离。如果您的相邻单词大于宽度,那么,一些相邻单词将不会被认为与当前单词相关。其默认值为 5。</strong></li> <li><strong>min_count:它表示单词在词汇表中出现的最小频率值。其默认值为 5。</strong></li> <li><strong>iter:它表示数据集上迭代/历元的数量。其默认值为 5。</strong></li> </ul> <h3 id="在-python-中使用-word2vec-的示例"><strong>在 Python 中使用 Word2Vec 的示例</strong></h3> <pre><code class="language-py">import string import nltk from nltk.corpus import brown from gensim.models import Word2Vec from sklearn.decomposition import PCA from matplotlib import pyplot nltk.download("brown") # Preprocessing data to lowercase all words and remove single punctuation words document = brown.sents() data = [] for sent in document: new_sent = [] for word in sent: new_word = word.lower() if new_word[0] not in string.punctuation: new_sent.append(new_word) if len(new_sent) > 0: data.append(new_sent) # Creating Word2Vec model = Word2Vec( sentences = data, size = 50, window = 10, iter = 20, ) # Vector for word love print("Vector for love:") print(model.wv["love"]) print() # Finding most similar words print("3 words similar to car") words = model.most_similar("car", topn=3) for word in words: print(word) print() #Visualizing data words = ["france", "germany", "india", "truck", "boat", "road", "teacher", "student"] X = model.wv[words] pca = PCA(n_components=2) result = pca.fit_transform(X) pyplot.scatter(result[:, 0], result[:, 1]) for i, word in enumerate(words): pyplot.annotate(word, xy=(result[i, 0], result[i, 1])) pyplot.show() </code></pre> <p><strong><strong>输出:</strong></strong></p> <pre><code class="language-py">Some Output[nltk_data] Downloading package brown to /root/nltk_data... [nltk_data] Unzipping corpora/brown.zip. Vector for love: [ 2.576164 -0.2537464 -2.5507743 3.1892483 -1.8316503 2.6448352 -0.06407754 0.5304831 0.04439827 0.45178193 -0.4788834 -1.2661372 1.0238386 0.3144989 -2.3910248 2.303471 -2.861455 -1.988338 -0.36665946 -0.32186085 0.17170368 -2.0292065 -0.9724318 -0.5792801 -2.809848 2.4033384 -1.0886359 1.1814215 -0.9120702 -1.1175308 1.1127514 -2.287549 -1.6190344 0.28058434 -3.0212548 1.9233572 0.13773602 1.5269752 -1.8643662 -1.5568101 -0.33570558 1.4902842 0.24851061 -1.6321756 0.02789219 -2.1180007 -1.5782264 -0.9047415 1.7374605 2.1492126 ] 3 words similar to car ('boat', 0.7544293403625488) ('truck', 0.7183066606521606) ('block', 0.6936473250389099) </code></pre> <p>**<img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f4eea8642ab889e0feebbe19f245a019.png" alt="Word2Vec Visualization" loading="lazy"></p> <p>Word2Vec Visualization**</p> <p><strong>在上面的可视化中,我们可以看到单词 student 和 teacher 指向一个方向,像印度、德国和法国这样的国家指向另一个方向,而像 road、boat 和 truck 这样的单词指向另一个方向。这表明我们的 Word2Vec 模型已经学习了可以根据词义区分单词的嵌入。</strong></p> <h3 id="使用-gensimd-加载预训练模型"><strong>使用 Gensimd 加载预训练模型</strong></h3> <p><strong>正如我们在下面看到的,Gensim 还带有几个已经预先训练好的模型。</strong></p> <pre><code class="language-py">import gensim import gensim.downloader for model_name in list(gensim.downloader.info()['models'].keys()): print(model_name) </code></pre> <pre><code class="language-py">fasttext-wiki-news-subwords-300 conceptnet-numberbatch-17-06-300 word2vec-ruscorpora-300 word2vec-google-news-300 glove-wiki-gigaword-50 glove-wiki-gigaword-100 glove-wiki-gigaword-200 glove-wiki-gigaword-300 glove-twitter-25 glove-twitter-50 glove-twitter-100 glove-twitter-200 __testing_word2vec-matrix-synopsis </code></pre> <p><strong>让我们加载<code>word2vec-google-news-300</code>模型并执行不同的任务,例如查找首都和国家之间的关系、获取相似的单词以及计算余弦相似度。</strong></p> <pre><code class="language-py">import gensim import gensim.downloader google_news_vectors = gensim.downloader.load('word2vec-google-news-300') # Finding Capital of Britain given Capital of France: (Paris - France) + Britain = print("Finding Capital of Britain: (Paris - France) + Britain") capital = google_news_vectors.most_similar(["Paris", "Britain"], ["France"], topn=1) print(capital) print() # Finding Capital of India given Capital of Germany: (Berlin - Germany) + India = print("Finding Capital of India: (Berlin - Germany) + India") capital = google_news_vectors.most_similar(["Berlin", "India"], ["Germany"], topn=1) print(capital) print() # Finding words similar to BMW print("5 similar words to BMW:") words = google_news_vectors.most_similar("BMW", topn=5) for word in words: print(word) print() # Finding words similar to Beautiful print("3 similar words to beautiful:") words = google_news_vectors.most_similar("beautiful", topn=3) for word in words: print(word) print() # Finding cosine similarity between fight and battle cosine = google_news_vectors.similarity("fight", "battle") print("Cosine similarity between fight and battle:", cosine) print() # Finding cosine similarity between fight and love cosine = google_news_vectors.similarity("fight", "love") print("Cosine similarity between fight and love:", cosine) </code></pre> <p>****输出<strong>:</strong></p> <pre><code class="language-py">[==================================================] 100.0% 1662.8/1662.8MB downloaded Finding Capital of Britain: (Paris - France) + Britain [('London', 0.7541897892951965)] Finding Capital of India: (Berlin - Germany) + India [('Delhi', 0.72683185338974)] 5 similar words to BMW: ('Audi', 0.7932199239730835) ('Mercedes_Benz', 0.7683467864990234) ('Porsche', 0.727219820022583) ('Mercedes', 0.7078384757041931) ('Volkswagen', 0.695941150188446) 3 similar words to beautiful: ('gorgeous', 0.8353004455566406) ('lovely', 0.810693621635437) ('stunningly_beautiful', 0.7329413890838623) Cosine similarity between fight and battle: 0.7021284 Cosine similarity between fight and love: 0.13506128 </code></pre> <h2 id="结论-14"><strong>结论</strong></h2> <p><strong>恭喜你!现在您已经知道了 Word2Vec 以及如何创建自己的模型来将单词转换成<a href="https://www.askpython.com/python-modules/numpy/vectorization-numpy" target="_blank">向量</a>。Word2Vec 广泛应用于许多领域,如文档相似性和检索、机器翻译等。现在您也可以在您的项目中使用它。</strong></p> <p><strong>感谢阅读!</strong></p> <h1 id="python-中的几何级数">Python 中的几何级数</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/geometric-progression-in-python" target="_blank">https://www.askpython.com/python/examples/geometric-progression-in-python</a></p> </blockquote> <p>嘿伙计们!在本教程中,我们将了解什么是几何级数,以及如何在 Python 编程语言中实现几何级数。</p> <hr> <h2 id="几何级数导论">几何级数导论</h2> <p>几何级数是一系列的元素,其中下一项是通过将前一项乘以公比而获得的。</p> <p>G.P .数列是一个数列,其中任何连续整数(项)的公比总是相同的。</p> <p>这个 G.P .级数的和是基于一个数学公式。</p> <pre><code class="language-py">Sn = a(r^n)/(1-r) Tn = ar^((n-1)) </code></pre> <hr> <h2 id="python-的几何进步">Python 的几何进步</h2> <p>让我们来了解一下 Python 中的几何级数是如何工作的。为了更好地理解,我们来看两个不同的例子。</p> <h3 id="1打印几何级数的前-n-项"><strong>1。打印几何级数的前 n 项</strong></h3> <p>实现 n GP 条款涉及许多步骤。步骤如下:</p> <p><strong>第一步</strong>——取 a(第一项)、r(公比)和 n(项数)的输入<br> <strong>第二步</strong>——从 1 到 n+1 进行循环,在每次迭代中计算第 n 项,并一直打印这些项。</p> <pre><code class="language-py"># 1\. Take input of 'a','r' and 'n' a = int(input("Enter the value of a: ")) r = int(input("Enter the value of r: ")) n = int(input("Enter the value of n: ")) # 2\. Loop for n terms for i in range(1,n+1): t_n = a * r**(i-1) print(t_n) </code></pre> <pre><code class="language-py">Enter the value of a: 1 Enter the value of r: 2 Enter the value of n: 10 1 2 4 8 16 32 64 128 256 512 </code></pre> <hr> <h3 id="2获取几何级数中前-n-项的和"><strong>2。获取几何级数中前 n 项的和</strong></h3> <p>计算前 n 个 GP 项的和需要几个步骤。步骤如下:</p> <p><strong><strong>第一步</strong></strong>——取 a(第一项)、r(公比)、n(项数)的输入<br> <strong>第二步</strong>——用上面提到的公式计算前‘n’项之和。</p> <pre><code class="language-py"># 1\. Take input of 'a','r' and 'n' a = int(input("Enter the value of a: ")) r = int(input("Enter the value of r: ")) n = int(input("Enter the value of n: ")) if(r>1): S_n = (a*(r**n))/(r-1) else: S_n = (a*(r**n))/(1-r) print("Sum of n terms: ",S_n) </code></pre> <pre><code class="language-py">Enter the value of a: 1 Enter the value of r: 2 Enter the value of n: 5 Sum of n terms: 32.0 </code></pre> <hr> <h2 id="结论-15"><strong>结论</strong></h2> <p>恭喜你!您刚刚学习了如何在 Python 中实现几何级数。希望你喜欢它!😇</p> <p>喜欢这个教程吗?无论如何,我建议你看一下下面提到的教程:</p> <ol> <li><a href="https://www.askpython.com/python/examples/memoization-in-python" target="_blank">Python 中的记忆化——简介</a></li> <li><a href="https://www.askpython.com/python/examples/anagrams-in-python" target="_blank">Python 中的字谜简介</a></li> <li><a href="https://www.askpython.com/python-modules/wonderwords-module" target="_blank">Python Wonderwords 模块——简介</a></li> </ol> <p>感谢您抽出时间!希望你学到了新的东西!!😄</p> <hr> <h1 id="如何获取一个-python-列表的第一个和最后一个元素">如何获取一个 Python 列表的第一个和最后一个元素?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/list/get-first-last-elements-python-list" target="_blank">https://www.askpython.com/python/list/get-first-last-elements-python-list</a></p> </blockquote> <p>序列数据是最常见的可用数据形式。一个 <a href="https://www.askpython.com/python/list/python-list" target="_blank">Python 列表</a>是 Python 中存储序列数据最常用的方式。</p> <h2 id="读取-python-列表的第一个和最后一个元素">读取 Python 列表的第一个和最后一个元素</h2> <p>列表中的元素从零开始编号。在本教程中,我们将学习访问列表中第一个和最后一个元素的不同方法。</p> <p>让我们从初始化一个列表开始。</p> <h3 id="1初始化-python-列表">1.初始化 Python 列表</h3> <p>要在 Python 中初始化列表,请使用:</p> <pre><code class="language-py">a = [6, 5, 9, 7] </code></pre> <p>这将用我们提到的四个元素初始化一个新的列表<strong>a</strong>。</p> <h3 id="2访问列表元素">2.访问列表元素</h3> <p>您可以通过使用列表名称和索引号来访问列表中的元素。要打印第一个元素,请使用:</p> <pre><code class="language-py">print(a[0]) </code></pre> <p>要打印最后一个元素,请使用:</p> <pre><code class="language-py">print(a[-1]) </code></pre> <p>使用 <strong>-1</strong> 作为索引给我们列表中的<strong>最后一个元素</strong>。</p> <h3 id="python-代码获取列表的第一个和最后一个元素">Python 代码获取列表的第一个和最后一个元素</h3> <p>完整的代码如下:</p> <pre><code class="language-py">a = [6, 5, 9, 7] print("first element is" ,a[0]) print("last element is", a[-1]) </code></pre> <p><strong>输出</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1005dceef36d27dfd2352c214f61a737.png" alt="First And Last Element" loading="lazy"></p> <h2 id="使用切片来检索第一个和最后一个元素">使用切片来检索第一个和最后一个元素</h2> <p>要使用<a href="https://www.askpython.com/python/array/array-slicing-in-python" target="_blank">切片</a>访问列表的第一个和最后一个元素,请使用以下代码行:</p> <pre><code class="language-py">ans = a[::len(a)-1] </code></pre> <p>这将把第一个和最后一个元素存储到 <strong>ans</strong> 变量中。</p> <h3 id="分割-python-列表的代码">分割 Python 列表的代码</h3> <pre><code class="language-py">a = [6, 5, 9, 7] ans = a[::len(a)-1] print ("The first and last elements of the list are : " + str(ans)) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7a225406502ff5d541de3cb4e77f496f.png" alt="Output" loading="lazy"></p> <p>Output</p> <h2 id="获取列表中每个元组的第一个元素">获取列表中每个元组的第一个元素</h2> <p>这个案例与上面的例子有一点不同。这里我们有一个<a href="https://www.askpython.com/python/tuple/python-tuple" target="_blank">元组</a>作为列表的一个元素。元组列表如下所示:</p> <pre><code class="language-py">[("a", "b", "c"), ("c", "d", "e"), ("f","g","h")] </code></pre> <p>我们必须得到每个元组的第一个元素。</p> <p>多亏了 Python,我们可以通过使用<a href="https://www.askpython.com/python/list/python-list-comprehension" target="_blank">列表理解</a>只用一行代码就做到这一点。</p> <pre><code class="language-py">first_tuple_elements = [a_tuple[0] for a_tuple in tuple_list] </code></pre> <p>这将创建元组的所有第一个元素的列表。要获得所有元组的最后一个元素,请用-1 替换 0。</p> <pre><code class="language-py">first_tuple_elements = [a_tuple[-1] for a_tuple in tuple_list] </code></pre> <p>这将创建一个包含元组中最后一个柠檬的列表。</p> <h3 id="检索列表中元组的第一个和最后一个元素">检索列表中元组的第一个和最后一个元素</h3> <p>完整的代码如下:</p> <pre><code class="language-py">tuple_list = [("a", "b", "c"),("c", "d", "e"), ("f","g","h")] first_tuple_elements = [a_tuple[0] for a_tuple in tuple_list] print(first_tuple_elements) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/df0b00b14aff7e0681a7c25cf058a064.png" alt="Tuple Output" loading="lazy"></p> <p>要从所有元组中获取最后的元素:</p> <pre><code class="language-py">tuple_list = [("a", "b", "c"),("c", "d", "e"), ("f","g","h")] first_tuple_elements = [a_tuple[-1] for a_tuple in tuple_list] print(first_tuple_elements) </code></pre> <h2 id="结论-16">结论</h2> <p>本教程是关于在 Python 中获取列表的第一个和最后一个元素。</p> <h1 id="如何在-python-熊猫中获取一个数据帧的索引">如何在 Python 熊猫中获取一个数据帧的索引?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/pandas/get-index-of-dataframe" target="_blank">https://www.askpython.com/python-modules/pandas/get-index-of-dataframe</a></p> </blockquote> <p>大家好!在本教程中,我们将讨论获取熊猫数据帧对象的索引或行的不同方法。那么,我们开始吧。</p> <hr> <h2 id="python-中获取数据帧索引的方法">Python 中获取数据帧索引的方法</h2> <p>让我们进入寻找数据帧索引的步骤。此外,查看如何<a href="https://www.askpython.com/python-modules/pandas/reset-index-of-a-dataframe" target="_blank">重置数据帧</a>的索引,以确保每次追加或排序数据帧时,索引号都是对齐的。</p> <h3 id="方法-1使用-for-循环">方法 1:使用 for 循环</h3> <p>在 Python 中,我们可以使用循环的<a href="https://www.askpython.com/course/python-course-for-loop" target="_blank">很容易地获得熊猫 DataFrame 对象的索引或行。在这个方法中,我们将使用 Python 中的</a> <a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">pandas 模块</a>的<code>pd.DataFrame()</code>函数从 <a href="https://www.askpython.com/python/dictionary/python-dictionary-comprehension" target="_blank">Python 字典</a>中创建一个 pandas DataFrame 对象。然后,我们将在 pandas DataFrame 索引对象上运行一个 for 循环来打印索引。让我们通过 Python 代码来实现这一点。</p> <pre><code class="language-py"># Method-1 # Import pandas import pandas as pd # Create a Python dictionary data = {"Name": ['Sanjay', 'Shreya', 'Raju', 'Gopal', 'Ravi'], "Roll": [101, 102, 103, 104, 105]} # Create a DataFrame object from above dictionary df = pd.DataFrame(data, index = [1, 2, 3, 4, 5]) print("This is DataFrame:\n") print(df) # Get the index/rows of the above DataFrame # Using for loop iteration print("\nThis is index of DataFrame:\n") for idx in df.index: print(idx, end = ' ') </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is DataFrame: Name Roll 1 Sanjay 101 2 Shreya 102 3 Raju 103 4 Gopal 104 5 Ravi 105 This is index of DataFrame: 1 2 3 4 5 </code></pre> <h3 id="方法-2使用索引属性">方法 2:使用索引属性</h3> <p>这是获取 DataFrame 对象索引的最广泛使用的方法。在这个方法中,我们将照常使用的<code>pd.DataFrame()</code>函数创建一个 pandas DataFrame 对象。然后我们将使用 pandas DataFrame 类的<code>index</code>属性来获取 pandas DataFrame 对象的索引。当我们在 pandas DataFrame 对象上应用<code>index</code>属性时,它返回一个包含 DataFrame 的<strong>索引列表</strong>的<a href="https://www.askpython.com/python/tuple/python-tuple" target="_blank">元组</a>。让我们看看如何在 Python 编程中实现这一点。</p> <pre><code class="language-py"># Method-2 # Import pandas import pandas as pd # Create a Python dictionary data = {"Name": ['Sanjay', 'Shreya', 'Raju', 'Gopal', 'Ravi'], "Roll": [101, 102, 103, 104, 105], "CGPA": [8.15, 8.18, 9.32, 8.85, 7.87]} # Create a DataFrame object from above dictionary df = pd.DataFrame(data, index = ['s1', 's2', 's3', 's4', 's5']) print("This is DataFrame:\n") print(df) # Get the index/rows of the above DataFrame # Using index attribute print("\nThis is index of DataFrame:\n") index_list = df.index print(index_list) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is DataFrame: Name Roll CGPA s1 Sanjay 101 8.15 s2 Shreya 102 8.18 s3 Raju 103 9.32 s4 Gopal 104 8.85 s5 Ravi 105 7.87 This is index of DataFrame: Index(['s1', 's2', 's3', 's4', 's5'], dtype='object') </code></pre> <h3 id="方法-3使用-indexvalues-属性">方法 3:使用 index.values 属性</h3> <p>首先,我们将使用 pd 创建一个熊猫 DataFrame 对象。熊猫 Python 模块的 DataFrame()函数。然后,我们将使用 pandas DataFrame 对象的 index.values 属性来访问它的索引列表。当我们在 pandas DataFrame 对象上应用 index.values 属性时,它返回一个数组,表示 pandas DataFrame 对象的索引列表中的数据。让我们进入 Python 代码来实现这种获取数据帧索引列表的方法。</p> <pre><code class="language-py"># Method-3 # Import pandas import pandas as pd # Create a Python dictionary data = {"Name": ['Sanjay', 'Shreya', 'Raju', 'Gopal', 'Ravi'], "Roll": [101, 102, 103, 104, 105], "Branch": ['ECE', 'CSE', 'EEE', 'ICE', 'IPE'], "CGPA": [8.15, 8.18, 9.32, 8.85, 7.87]} # Create a DataFrame object from above dictionary df = pd.DataFrame(data) print("This is DataFrame:\n") print(df) # Get the index/rows of the above DataFrame # Using index.values property print("\nThis is index of DataFrame:\n") index_list = df.index.values print(index_list) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is DataFrame: Name Roll Branch CGPA 0 Sanjay 101 ECE 8.15 1 Shreya 102 CSE 8.18 2 Raju 103 EEE 9.32 3 Gopal 104 ICE 8.85 4 Ravi 105 IPE 7.87 This is index of DataFrame: [0 1 2 3 4] </code></pre> <h3 id="方法-4使用-tolist函数">方法 4:使用 tolist()函数</h3> <p>这是 pandas 模块的一个便利工具,它将 pandas DataFrame 对象的索引转换成一个 <a href="https://www.askpython.com/python/difference-between-python-list-vs-array" target="_blank">Python 列表</a>。在这个方法中,我们使用 pd 创建一个 pandas DataFrame 对象。DataFrame()函数,就像我们在前面的方法中所做的那样。然后我们将使用 pandas DataFrame 类的<code>index</code>属性访问 pandas DataFrame 索引对象。最后,我们将应用<code>tolist()</code>函数,它实际上以 Python 列表的形式返回数据帧的索引。让我们编写 Python 程序来实现这个方便的方法,以获得 Python 列表中熊猫数据帧的索引。</p> <pre><code class="language-py"># Method-4 # Import pandas import pandas as pd # Create a Python dictionary data = {"Name": ['Sanjay', 'Shreya', 'Raju', 'Gopal', 'Ravi'], "Roll": [101, 102, 103, 104, 105], "Branch": ['ECE', 'CSE', 'EEE', 'ICE', 'IPE'], "CGPA": [8.15, 8.18, 9.32, 8.85, 7.87]} # Create a DataFrame object from above dictionary df = pd.DataFrame(data, index = ['R1', 'R2', 'R3', 'R4', 'R5']) print("This is DataFrame:\n") print(df) # Get the index/rows of the above DataFrame # Using tolist() function print("\nThis is index of DataFrame:\n") index_list = df.index.tolist() print(index_list) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is DataFrame: Name Roll Branch CGPA R1 Sanjay 101 ECE 8.15 R2 Shreya 102 CSE 8.18 R3 Raju 103 EEE 9.32 R4 Gopal 104 ICE 8.85 R5 Ravi 105 IPE 7.87 This is index of DataFrame: ['R1', 'R2', 'R3', 'R4', 'R5'] </code></pre> <h3 id="方法-5使用-query和-tolist函数">方法 5:使用 query()和 tolist()函数</h3> <p>使用这种方法,我们可以只获得 pandas DataFrame 对象的满足特定标准的特定索引。在这个方法中,我们将使用<code>pd.DataFrame()</code>函数创建一个 pandas DataFrame 对象,并使用 pandas DataFrame 类的<code>query()</code>函数。当我们在数据帧上应用<code>query()</code>函数并传递一个条件时,它返回一个数据帧,该数据帧只包含满足传递给它的条件的行。</p> <p>之后,我们将应用 DataFrame 类的<code>index</code>属性,并使用<code>tolist()</code>函数返回 DataFrame 索引值的 Python 列表。</p> <p>让我们看看实现这个有用方法的 Python 代码,以获得满足给定条件的 pandas DataFrame 对象的选定行或索引。</p> <pre><code class="language-py"># Method-5 # Import pandas import pandas as pd # Create a Python dictionary data = {"Name": ['Sanjay', 'Shreya', 'Raju', 'Gopal', 'Ravi'], "Roll": [101, 102, 103, 104, 105], "Branch": ['ECE', 'CSE', 'EEE', 'ICE', 'IPE'], "CGPA": [8.15, 9.32, 8.78, 7.87, 8.85]} # Create a DataFrame object from above dictionary df = pd.DataFrame(data, index = ['I', 'II', 'III', 'IV', 'V']) print("This is DataFrame:\n") print(df) # Get the index/rows of the above DataFrame # Using query() and tolist() functions print("\nThis is index of DataFrame:\n") index_list = df.query("CGPA > 8.5").index.tolist() print(index_list) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is DataFrame: Name Roll Branch CGPA I Sanjay 101 ECE 8.15 II Shreya 102 CSE 9.32 III Raju 103 EEE 8.78 IV Gopal 104 ICE 7.87 V Ravi 105 IPE 8.85 This is index of DataFrame: ['II', 'III', 'V'] </code></pre> <h2 id="总结">总结</h2> <p>在本教程中,我们学习了四种不同的方法来获取 DataFrame 对象的索引。希望你已经理解了以上内容,并对自己尝试这些方法感到兴奋。谢谢你,请继续关注我们的更多这类 Python 教程。</p> <h1 id="如何在-python-中获取电话号码信息">如何在 Python 中获取电话号码信息?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/get-phone-number-information" target="_blank">https://www.askpython.com/python/examples/get-phone-number-information</a></p> </blockquote> <p>在本教程中,我们将看看如何在 Python 中获取电话号码信息。“phonenumbers”这个名字指的是一个非常有趣和方便的库。这是一个库,它将帮助我们在 Python 中体验电话号码的乐趣。</p> <h2 id="用-python-获取电话号码信息的步骤">用 Python 获取电话号码信息的步骤</h2> <p>我们将利用 phonenumbers 库来获取有关电话号码的信息。让我们更深入地了解这一课。</p> <p>首先,在命令提示符下运行下面一行来安装 phonenumbers 库。</p> <pre><code class="language-py">pip install phonenumbers </code></pre> <hr> <h3 id="将字符串转换为电话号码格式">将字符串转换为电话号码格式</h3> <p>为了研究 phonenumbers 模块的功能,我们必须首先获得 phone number 格式的用户电话号码。在这一节中,我们将了解如何将用户的电话号码转换为 phone number 格式。</p> <p>输入必须是字符串类型,国家代码必须在电话号码之前。</p> <pre><code class="language-py">import phonenumbers pN = phonenumbers.parse("+919876643290") print(pN) </code></pre> <pre><code class="language-py">Country Code: 91 National Number: 9876643290 </code></pre> <hr> <h3 id="获取时区">获取时区</h3> <p>下面是一个简单的 Python 程序,它使用 phonenumbers 模块来确定电话号码的时区。</p> <p>首先,我们将字符串输入转换为电话号码格式,然后我们利用一个内置的方法来确定用户的时区。它只返回有效数字的结果。</p> <pre><code class="language-py">import phonenumbers from phonenumbers import timezone pN = phonenumbers.parse("+919876643290") tZ = timezone.time_zones_for_number(pN) print(tZ) </code></pre> <pre><code class="language-py">('Asia/Calcutta',) </code></pre> <hr> <h3 id="从文本中提取电话号码">从文本中提取电话号码</h3> <p>使用这个模块,我们可以从文本/段落中提取电话号码。您可以遍历它来获得电话号码列表。PhoneNumberMatcher 对象为此提供了必要的方法。</p> <pre><code class="language-py">import phonenumbers T = "Contact us at +919876643290 or +14691674587" N = phonenumbers.PhoneNumberMatcher(T, "IN") for n in N: print(n) </code></pre> <pre><code class="language-py">PhoneNumberMatch [14,27) +919876643290 </code></pre> <hr> <h3 id="电话号码的运营商和地区">电话号码的运营商和地区</h3> <p>我们将学习如何使用本模块的地理编码器和运营商功能来确定电话号码的运营商和区域。</p> <pre><code class="language-py">import phonenumbers from phonenumbers import geocoder, carrier pN = phonenumbers.parse("+919876643290") C = carrier.name_for_number(pN, 'en') R = geocoder.description_for_number(pN, 'en') print(C) print(R) </code></pre> <pre><code class="language-py">Airtel India </code></pre> <hr> <h2 id="结论-17">结论</h2> <p>恭喜你!您刚刚学习了如何在 Python 中获取电话号码信息。希望你喜欢它!😇</p> <p>喜欢这个教程吗?无论如何,我建议你看一下下面提到的教程:</p> <ol> <li><a href="https://www.askpython.com/python/python-convert-number-to-words" target="_blank">Python:将数字转换成文字</a></li> <li><a href="https://www.askpython.com/python/examples/convert-number-to-words" target="_blank">在 Python 中把一个数字转换成单词【一个数字接一个数字】</a></li> <li><a href="https://www.askpython.com/python/examples/smallest-number-in-python" target="_blank">在 Python 中寻找最小数字的 3 种简单方法</a></li> </ol> <p>感谢您抽出时间!希望你学到了新的东西!!😄</p> <hr> <h1 id="获取-python-列表中项目的索引3-种简单的方法">获取 Python 列表中项目的索引——3 种简单的方法</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/list/get-the-index-of-an-item" target="_blank">https://www.askpython.com/python/list/get-the-index-of-an-item</a></p> </blockquote> <p>读者朋友们,你们好!希望你们都过得好。在本文中,我们将重点关注获取 Python 列表中元素索引的<strong>不同技术。</strong></p> <p>那么,让我们开始吧。</p> <hr> <h2 id="什么是-python-列表">什么是 Python 列表?</h2> <p>一个 <a href="https://www.askpython.com/python/list/python-list" target="_blank">Python 列表</a>是一个数据结构,它有效地扮演了一个<a href="https://www.askpython.com/python/array/python-array-examples" target="_blank">数组</a>的角色。此外,“列表”以动态方式存储元素,并可用于存储不同类型的元素,这与数组不同。</p> <p>因此,列表可以被认为是数组数据结构的更好的替代物,并且可以保存完全不同的元素。</p> <hr> <h2 id="如何获取-python-列表中某项的索引">如何获取 Python 列表中某项的索引?</h2> <p>理解了 Python List 的工作原理之后,现在让我们开始用不同的方法来获取列表中一个条目的索引。</p> <h3 id="方法一列表理解">方法一:列表理解</h3> <p><a href="https://www.askpython.com/python/list/python-list-comprehension" target="_blank">Python List Comprehension</a> 可用于利用列表中特定元素的所有出现的索引列表。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">[expression for element in iterator if condition] </code></pre> <p>使用<code>List comprehension</code>,我们可以得到一个项目在列表中所有出现的索引值,即<strong>位置。</strong></p> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10,20,30,10,50,10,45,10] print ("List : " ,lst) res = [x for x in range(len(lst)) if lst[x] == 10] print ("Indices at which element 10 is present: " + str(res)) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">List : [10, 20, 30, 10, 50, 10, 45, 10] Indices at which element 10 is present: [0, 3, 5, 7] </code></pre> <hr> <h3 id="方法-2使用-index方法">方法 2:使用 index()方法</h3> <p>Python 内置的 index()方法可以用来获取列表中特定元素的索引值。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">index(element,start,end) </code></pre> <p><code>start</code> 和<code>end</code> 参数是可选的,代表执行搜索的位置范围。</p> <p>与其他方法不同,index()方法只返回列表中特定项目第一次出现的索引值。</p> <p>如果所提到的元素不在列表中,则引发<code>ValueError exception</code>。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10,20,30,10,50,10,45,10] print ("List : " ,lst) print("Index at which element 10 is present :",lst.index(10)) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">List : [10, 20, 30, 10, 50, 10, 45, 10] Index at which element 10 is present : 0 </code></pre> <hr> <h3 id="方法-3使用-enumerate函数">方法 3:使用 enumerate()函数</h3> <p><a href="https://www.askpython.com/python/built-in-methods/python-enumerate-method" target="_blank">Python enumerate()方法</a>也可以用于<strong>返回特定元素</strong>在列表中所有出现的索引位置。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10,20,30,10,50,10,45,10] print ("List : " ,lst) res = [x for x, z in enumerate(lst) if z == 10] print ("Indices at which element 10 is present: " + str(res)) </code></pre> <p>这里,<code>enumerate() method</code>设置了一个计数器,它在每次成功搜索该特定项目后递增,并返回它的索引值。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">List : [10, 20, 30, 10, 50, 10, 45, 10] Indices at which element 10 is present: [0, 3, 5, 7] </code></pre> <hr> <h2 id="结论-18">结论</h2> <p>到此,我们就结束了这个话题。如果你遇到任何问题,欢迎在下面评论。在那之前,学习愉快!!</p> <hr> <h2 id="参考-3">参考</h2> <ul> <li><a href="https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list" target="_blank">如何获取 Python 列表中某项的索引— StackOverflow</a></li> </ul> <h1 id="梯度推进模型用-python-实现">梯度推进模型——用 Python 实现</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/gradient-boosting-model-in-python" target="_blank">https://www.askpython.com/python/examples/gradient-boosting-model-in-python</a></p> </blockquote> <p>读者朋友们,你们好!在本文中,我们将关注 Python 中的<strong>梯度增强模型,以及实现细节。</strong></p> <p>所以,让我们开始吧!</p> <hr> <h2 id="第一什么是梯度提升模型">第一,什么是梯度提升模型?</h2> <p>在深入探讨梯度提升的概念之前,我们先来了解一下机器学习中的提升概念。</p> <p>Boosting 技术试图通过以串行方式构建弱模型实例来创建强回归器或分类器。也就是说,前一个实例的<strong>错误分类误差</strong>被馈送到下一个实例,并且它从该误差中学习以提高分类或预测率。</p> <p>梯度推进算法就是这样一种机器学习模型,它遵循预测推进技术。</p> <p>在梯度推进算法中,预测器的每个实例从其前一个实例的误差中学习,即它校正由前一个预测器报告或引起的误差,以具有更好的模型和更少的误差率。</p> <p>每个梯度提升算法的基础学习器或预测器是<strong>分类和回归树</strong>。学习的过程继续进行,直到我们决定构建的所有 N 棵树都已经从模型中学习,并且准备好进行具有更少量的错误分类错误的预测。</p> <p>梯度推进模型适用于回归和分类变量。</p> <p><em><strong>推荐阅读——<a href="https://www.askpython.com/python/examples/gradient-boosting" target="_blank">Python XGBoost 教程</a></strong></em></p> <hr> <h2 id="梯度推进模型一种实用的方法">梯度推进模型——一种实用的方法</h2> <p>在本例中,我们利用了自行车租赁计数预测数据集。你可以在这里找到数据集<a href="https://github.com/Safa1615/BIKE-RENTAL-COUNT/blob/master/day.csv" target="_blank">!</a></p> <p>首先,我们使用 <a href="https://www.askpython.com/python-modules/python-csv-module" target="_blank">read_csv()</a> 函数将数据集加载到 Python 环境中。</p> <p>为了进一步实现,我们使用来自<code>sklearn.model selection</code>库的<code>train_test_split()</code>函数将数据集分成训练和测试数据值。</p> <p>分离数据后,我们进一步使用 <a href="https://www.askpython.com/python/examples/mape-mean-absolute-percentage-error" target="_blank">MAPE</a> 作为评估算法的误差度量模型。</p> <p>现在,让我们来关注一下在 Python 中实现梯度推进模型的步骤</p> <ul> <li>我们利用 GradientBoostingRegressor()函数对训练数据应用 GBM。</li> <li>在此基础上,我们利用 predict()方法对测试数据进行建模。</li> </ul> <p><strong>举例:</strong></p> <pre><code class="language-py">import pandas BIKE = pandas.read_csv("day.csv") #Separating the depenedent and independent data variables into two dataframes. from sklearn.model_selection import train_test_split X = bike.drop(['cnt'],axis=1) Y = bike['cnt'] # Splitting the dataset into 80% training data and 20% testing data. X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.20, random_state=0) import numpy as np def MAPE(Y_actual,Y_Predicted): mape = np.mean(np.abs((Y_actual - Y_Predicted)/Y_actual))*100 return mape from sklearn.ensemble import GradientBoostingRegressor GR = GradientBoostingRegressor(n_estimators = 200, max_depth = 1, random_state = 1) gmodel = GR.fit(X_train, Y_train) g_predict = gmodel.predict(X_test) GB_MAPE = MAPE(Y_test,g_predict) Accuracy = 100 - GB_MAPE print("MAPE: ",GB_MAPE) print('Accuracy of Linear Regression: {:0.2f}%.'.format(Accuracy)) </code></pre> <p><strong>输出:</strong></p> <p>结果,我们从数据集上的梯度推进模型获得了 83.10%的准确度。</p> <pre><code class="language-py">MAPE: 16.898145257306943 Accuracy of Linear Regression: 83.10%. </code></pre> <hr> <h2 id="结论-19">结论</h2> <p>到此,我们就结束了这个话题。如果你遇到任何问题,欢迎在下面评论。</p> <p>更多与 Python 编程相关的帖子,请继续关注我们。</p> <p>在那之前,学习愉快!!🙂</p> <h1 id="使用-python-xgboost-进行梯度增强">使用 Python XGBoost 进行梯度增强</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/gradient-boosting" target="_blank">https://www.askpython.com/python/examples/gradient-boosting</a></p> </blockquote> <p>我过去参加过很多 Kaggle 比赛,在过去的 3-4 年里,所有的顶级获奖作品都使用了某种形式的渐变效果。所以,今天我们就来仔细看看。</p> <h2 id="什么是梯度增强">什么是梯度增强?</h2> <p><strong>集成学习</strong>:为了获得比单独从任何组成学习算法中提取的预测效率更高的预测效率,集成方法使用多种学习算法。</p> <p>个体模型中存在偏差或方差是很常见的,这就是为什么我们需要学习集成学习。</p> <p><strong>装袋</strong>和<strong>助推</strong>是两种最常见的合奏技术。</p> <ul> <li><strong>装袋</strong>:大量模型平行训练。每个模型由数据的随机子集训练。</li> <li><strong>助推</strong>:顺序示教大量附加模型。从先前模型所犯的错误中,每个特定的模型都会学习。</li> </ul> <p>虽然你之前已经学过<strong>装袋</strong>技术(比如<a href="https://www.askpython.com/python/examples/random-forest-regression" target="_blank">随机森林</a>),但是让我们来看看什么是助推。</p> <p>一类<a href="https://www.askpython.com/python/examples/knn-in-python" target="_blank">机器学习算法</a>,将几个弱学习模型合并在一起,产生一个强预测模型,称为<strong>梯度推进分类器</strong>。</p> <p>当进行梯度提升时,通常使用决策树。由于梯度推进模型在对复杂数据集进行分类方面的有效性,它们正变得越来越常见,并且最近已经被用于在 <a href="https://www.kaggle.com/" target="_blank">Kaggle</a> 数据科学中赢得几场比赛!</p> <p><strong><a href="https://www.askpython.com/python/examples/split-data-training-and-testing-set" target="_blank">Scikit-Learn</a></strong> ,Python 机器学习库,支持各种梯度提升分类器实现,包括 XGBoost、light Gradient Boosting、catBoosting 等。</p> <h2 id="xgboost-是什么">XGBoost 是什么?</h2> <p>XGBoost 是处理标准表格数据的领先模型(与图像和视频等更奇特的数据类型相反,这些数据类型存储在 <a href="https://www.askpython.com/python-modules/pandas/dataframes-in-python" target="_blank">Pandas DataFrames</a> 中)。很多 Kaggle 比赛都是以 XGBoost 车型为主。</p> <p>与随机森林等策略相比,XGBoost 模型需要更多的专业知识和模型调整来实现最佳精度。</p> <p>而且超级简单。</p> <h2 id="房价数据集上梯度推进的实现">房价数据集上梯度推进的实现</h2> <p>我正在使用一个来自 Kaggle.com 的非常受欢迎的数据集,叫做房价预测(HPP)数据集。</p> <p>这个竞赛用 79 个解释变量描述了(几乎)爱荷华州埃姆斯住宅的方方面面,挑战你预测每栋房子的最终价格。</p> <p>我们开始吧!</p> <h3 id="1导入所需的包">1.导入所需的包</h3> <p>让我们导入我们的重要包:</p> <pre><code class="language-py">import pandas as pd from sklearn.model_selection import train_test_split from sklearn.impute import SimpleImputer from xgboost import XGBRegressor </code></pre> <p>估算器用于使用平均值、众数或任何其他选择的方法来“估算”(替换)数据集中的 NaN 值。</p> <h3 id="2设置数据">2.设置数据</h3> <p>让我们导入我们的培训数据:</p> <pre><code class="language-py">data_train = pd.read_csv('train.csv') data_train.dropna(axis=0, subset=['SalePrice'], inplace=True) data_train.head(1) </code></pre> <p>我们删除了那些在 <strong>SalePrice</strong> 中有 NaN 的行,因为这是我们最重要的度量。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ccd778ce5b612cbb4561b482f077dd39.png" alt="Dataset House Price Prediction With Gradient Boosting" loading="lazy"></p> <p>Dataset House Price Prediction With Gradient Boosting</p> <p>我们将指定销售价格作为标签(即 AX = y 格式):</p> <pre><code class="language-py">y = data_train.SalePrice X = data_train.drop(['SalePrice'], axis=1).select_dtypes(exclude=['object']) </code></pre> <p>我们<a href="https://www.askpython.com/python/examples/split-data-training-and-testing-set" target="_blank">使用 sklearn 的 train_test_split 函数,以 3:1 的比例将数据分为训练和测试数据</a>:</p> <pre><code class="language-py">train_X, test_X, train_y, test_y = train_test_split(X.values, y.values, test_size=0.25) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e7dac7bdb134fb78ff28a1bfe700e69b.png" alt="Train Data House Price Prediction" loading="lazy"></p> <p>Train Data House Price Prediction</p> <p>让我们<a href="https://www.askpython.com/python/examples/impute-missing-data-values" target="_blank">估算数据集中的 NaN 值</a>:</p> <pre><code class="language-py">my_imputer = SimpleImputer() train_X = my_imputer.fit_transform(train_X) test_X = my_imputer.transform(test_X) </code></pre> <p>我们现在已经完成了预处理。很明显,我们可以调整数据集的每一列,<a href="https://www.askpython.com/python/examples/detection-removal-outliers-in-python" target="_blank">发现异常值</a>,调整等等。但那是你的作业!</p> <h3 id="3创建模型">3.创建模型</h3> <p>让我们创建我们的模型:</p> <pre><code class="language-py">my_model = XGBRegressor() my_model.fit(train_X, train_y, verbose=True) </code></pre> <p>正如您在输出中看到的,这些都是我们可以指定来调整模型的参数:</p> <pre><code class="language-py">XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, gamma=0, importance_type='gain', learning_rate=0.1, max_delta_step=0, max_depth=3, min_child_weight=1, missing=None, n_estimators=100, n_jobs=1, nthread=None, objective='reg:linear', random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=None, subsample=1, verbosity=1) </code></pre> <p>我们现在可以做出预测了:</p> <pre><code class="language-py">predictions = my_model.predict(test_X) predictions </code></pre> <p>这给了我们:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e0b427eb8da10b3dd18d22b41d1a55db.png" alt="Predicted Outputs House Prices In Iowa Kaggle" loading="lazy"></p> <p>Predicted Outputs House Prices In Iowa, Kaggle</p> <p>我们还可以找到我们的<a href="https://www.askpython.com/python/examples/mape-mean-absolute-percentage-error" target="_blank">回归误差</a>,它对我们来说大约是 17000。:</p> <pre><code class="language-py">from sklearn.metrics import mean_absolute_error print("Mean Absolute Error : " + str(mean_absolute_error(predictions, test_y))) </code></pre> <h2 id="梯度增强的完整代码实现">梯度增强的完整代码实现</h2> <p>如果您错过了任何一步,您可以在这里找到完整的代码和数据集:</p> <p><a href="https://github.com/arkaprabha-majumdar/house-price-prediction" target="_blank"><strong>https://github . com/arkaprabha-Majumdar/house-price-prediction</strong></a></p> <h2 id="其他形式轻型-gbm-和-catboost">其他形式–轻型 GBM 和 catBoost</h2> <p>用法与 XGB 完全相同:</p> <pre><code class="language-py">from lightgbm import LGBMRegressor my_model = LGBMRegressor() my_model.fit(train_X, train_y, verbose=True) </code></pre> <p>和</p> <pre><code class="language-py">from catboost import CatBoostRegressor my_model = CatBoostRegressor() my_model.fit(train_X, train_y, verbose=True) </code></pre> <p>过程是一样的。</p> <p><strong>LightGBM</strong> : Light GBM 基于决策树算法,是一个快速、分布式、高性能的梯度推进系统,用于机器学习中的排序、分类和许多其他任务。</p> <p>它以叶的方式划分树以获得最佳匹配,而其他提升算法以深度或级别的方式而不是以叶的方式来分解树。</p> <p>因此,当在轻 GBM 中在同一叶上增加时,逐叶算法可以比逐级算法最小化更多的损耗,从而产生高得多的精度,这是任何电流提升算法都很难实现的。</p> <p>令人惊讶的是,它也非常快。lightGBM 的训练程序在执行时间上有很大的差异,所以现在更倾向于作为一种"<strong>快速修复</strong>"</p> <p><strong>Catboost</strong> :作为一种更好的梯度提升算法,CatBoost 实现了有序提升,但 CatBoost 最大的进步是它如何处理分类信息。因为它需要提供一个数字编码,分类数据引入了许多问题。</p> <p>Catboost 使用一个目标编码变体,该变体使用可用的历史记录和随机排列来确定目标编码,从而对我们的分类数据进行编码和处理。Catboost 不使用平均值,而是使用可用的上下文,因为实时运行的模型不知道其目标的真实平均值。</p> <p>有几个基准测试,人们已经完成了上述所有算法。浏览它们:</p> <p><a href="https://www.kaggle.com/nholloway/catboost-v-xgboost-v-lightgbm" target="_blank">https://www . ka ggle . com/n Holloway/catboost-v-xgboost-v-light GBM</a></p> <p>但是,总体来说,catBoost 速度慢,效果不太好。尝试做你自己的基准测试,并在评论中告诉我们你更喜欢哪一个。</p> <h2 id="结论-20">结论</h2> <p>梯度推进是一种强大的数据分类和回归机制,可以加快您学习新机器学习算法的速度。</p> <h1 id="使用-python-查找图像的渐变">使用 Python 查找图像的渐变</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/gradient-of-an-image" target="_blank">https://www.askpython.com/python/examples/gradient-of-an-image</a></p> </blockquote> <p>在本教程中,我们将学习如何用 Python 来计算图片的渐变。完成本课程后,你将能够识别图片在 X、Y 和两个方向的渐变,并利用几个有用的库。</p> <p>渐变图片只不过是图像颜色在 X、Y 或两个方向上的强度变化。</p> <p>可以使用图像的 Sobel 和 Laplacian 导数来确定图片的梯度。Sobel 可用于 X 或 Y 方向,或两个方向,但拉普拉斯算子在两个方向都有帮助。</p> <hr> <h2 id="导入所需模块">导入所需模块</h2> <p>首先,我们导入 OpenCV cv2 库、Numpy 和 Matplotlib。接下来,我们使用 cv2 的 imread()方法和两个参数来读取图片。</p> <p>第一个是我们的图片名和扩展名(确保它和图片在同一个文件夹中),第二个是比例类型,只能是数字形式的 0,1,-1。灰度、颜色和无变化是三种比例类型。</p> <pre><code class="language-py">import cv2 import numpy as np import matplotlib.pyplot as plot image = cv2.imread("fig.jpg",0) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8ae25cc44d73fb64e1598b2cd0f3c5d1.png" alt="Gradient Of An Image Input" loading="lazy"></p> <p>Gradient Of An Image Input</p> <hr> <h2 id="使用-python-查找图像的渐变-1">使用 Python 查找图像的渐变</h2> <p>接下来,我们将使用 Python Laplacian()通过给出三个参数来确定图像的 Laplacian 导数。第一个是我们的图像变量,第二个是 cv2 的数据类型 CV 64F,第三个是内核大小。3 表示 ksize(确保始终使用奇数)</p> <p>ksize 的值增加了边的厚度。ksize 3 将获得最大的结果。接下来,我们将该值转换为 Numpy 的 uint8 类型的无符号 8 位整数。</p> <p>之后,我们使用 cv2 的 Sobel()通过提供四个参数来计算图片在 x 或 y 方向上的梯度:第一个是图像源,第二个是深度,第三个是 x 导数,第四个是 y 方向上的 y 导数 dy。</p> <pre><code class="language-py">lap = cv2.Laplacian(image,cv2.CV_64F,ksize=3) lap = np.uint8(np.absolute(lap)) sobelx= cv2.Sobel(image,0, dx=1,dy=0) sobelx= np.uint8(np.absolute(sobelx)) sobely= cv2.Sobel(image,0, dx=0,dy=1) sobely = np.uint8(np.absolute(sobely)) </code></pre> <p>最后,我们制作两个列表:一个用于标题,另一个用于由拉普拉斯算子、sobelx 和 sobely 创建的图片。</p> <p>在利用 matplotlib 之后,我们使用 imshow()函数在屏幕上绘图,提供两个参数:一个用于图像源,一个用于背景。yticks()和 xticks()可以与列表(可以是空的)一起使用,以设置 x 和 y 方向的标签。</p> <pre><code class="language-py">results = [lap,sobelx,sobely] images =["Gradient Img","Gradient_X","Gradient_Y"] plt.figure(figsize=(10,10)) for i in range(3): plot.title(results[i]) plot.subplot(1,3,i+1) plot.imshow(results[i],"plasma") plot.xticks([]) plot.yticks([]) plot.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/38e3ce9e37d69507596dbd90f8eeb1d5.png" alt="Gradient Of An Image Output" loading="lazy"></p> <p>Gradient Of An Image Output</p> <hr> <h2 id="结论-21">结论</h2> <p>恭喜你!你刚刚学习了如何获取图像的渐变。希望你喜欢它!😇</p> <p>喜欢这个教程吗?无论如何,我建议你看一下下面提到的教程:</p> <ol> <li><a href="https://www.askpython.com/python/examples/gradient-boosting-model-in-python" target="_blank">渐变助推模型——用 Python 实现</a></li> <li><a href="https://www.askpython.com/python/examples/gradient-boosting" target="_blank">使用 Python XGBoost 进行梯度增强</a></li> </ol> <p>感谢您抽出时间!希望你学到了新的东西!!😄</p> <hr> <h1 id="用-python-实现图形">用 Python 实现图形</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/graph-in-python" target="_blank">https://www.askpython.com/python/examples/graph-in-python</a></p> </blockquote> <p>图形是一种数据结构,用于说明两个对象之间的联系。图的一个简单例子是地理地图,其中不同的地方用道路连接起来。在本文中,我们将研究图数据结构的理论方面。此外,我们将使用两种不同的方法实现一个图形。</p> <h2 id="什么是图">什么是图?</h2> <p>图形是一种非线性数据结构,用于表示相互连接的对象。对象被称为顶点,它们之间的链接被称为边。</p> <p>在数学上,图 G 被定义为两个集合 V 和 E 的有序对。它被表示为 G=(V,E)其中,</p> <ul> <li>v 是图中顶点的集合。</li> <li>e 是图中存在的边的集合。每条边都用一个元组来表示,元组显示了它所连接的顶点。例如,如果边“e”连接顶点 v1 和 v2,它将被表示为(v1,v2)。</li> </ul> <p>为了更清楚地理解这一点,让我们看下面的例子。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5881ab97e34a7a44225b1fb5ded95f10.png" alt="Graph Implementation In Python- Askpython" loading="lazy"></p> <p>Graph Implementation In Python – Askpython</p> <p>在上图中,我们有一个包含 6 个顶点的图,即 0,1,2,3,4,5。因此,等式 G=(V,E)中的集合 V 将是顶点的集合,其将被表示如下。</p> <pre><code class="language-py">V={0,1,2,3,4,5} </code></pre> <p>为了找到由边组成的集合 E,我们将首先找到每条边。在上图中,我们有 8 条线连接图形的不同顶点。</p> <p>我们使用顶点连接的名称来定义每个顶点“v”。例如,连接 0 到 1 的边将被称为 e01,并且将使用元组(0,1)来表示。类似地,所有的边将被定义如下。</p> <pre><code class="language-py">e01=(0,1) e12=(1,2) e03=(0,3) e13=(1,3) e34=(3,4) e25=(2,5) e45=(4,5) e24=(2,4) </code></pre> <p>由图中每条边组成的集合 E 定义如下。</p> <pre><code class="language-py"> E={(0,1),(1,2),(0,3),(1,3),(3,4),(2,5),(4,5),(2,4)}. </code></pre> <p>由于我们已经获得了该图的数学符号,现在我们将用 python 实现它。</p> <h2 id="如何用-python-实现一个使用邻接矩阵的图">如何用 Python 实现一个使用邻接矩阵的图?</h2> <p>如果我们有一个有 N 个顶点的图,这个图的邻接矩阵将是一个二维矩阵。矩阵中的行和列表示图的顶点,矩阵中的值决定两个顶点之间是否有边。</p> <p>假设我们有任何图的邻接矩阵 A。对于任意索引(I,j),如果顶点 I 和顶点 j 之间有边,我们给 A[i][j]赋值 1。当顶点 I 和 j 之间不存在边时,值 0 被分配给 A[i][j]。这可以用 Python 实现,如下所示。</p> <pre><code class="language-py">import numpy as np # keep vertices in a set vertices = {0, 1, 2, 3, 4, 5} # keep edges in a set edges = {(0, 1), (1, 2), (0, 3), (1, 3), (3, 4), (2, 5), (4, 5), (2, 4)} # create a 6X6 integer numpy array with all values initialised to zero adjacencyMatrix = np.zeros((6, 6)).astype(int) # Represent edges in the adjacency matrix for edge in edges: v1 = edge[0] v2 = edge[1] adjacencyMatrix[v1][v2] = 1 adjacencyMatrix[v2][v1] = 1 # if v1 is connected to v2, v2 is also connected to v1 print("The set of vertices of the graph is:") print(vertices) print("The set of edges of the graph is:") print(edges) print("The adjacency matrix representing the graph is:") print(adjacencyMatrix) </code></pre> <p>输出:</p> <pre><code class="language-py">The set of vertices of the graph is: {0, 1, 2, 3, 4, 5} The set of edges of the graph is: {(0, 1), (2, 4), (1, 2), (3, 4), (0, 3), (4, 5), (2, 5), (1, 3)} The adjacency matrix representing the graph is: [[0 1 0 1 0 0] [1 0 1 1 0 0] [0 1 0 0 1 1] [1 1 0 0 1 0] [0 0 1 1 0 1] [0 0 1 0 1 0]] </code></pre> <p>使用邻接矩阵实现图有一个缺点。这里,我们为每个顶点分配内存,不管它是否存在。这可以通过使用邻接表实现图来避免,如下节所述。</p> <h2 id="如何用-python-实现一个使用邻接表的图">如何用 Python 实现一个使用邻接表的图?</h2> <p>邻接表存储每个顶点的所有连接顶点的列表。为了实现这一点,我们将使用一个字典,其中字典的每个键代表一个顶点,键的值包含该关键顶点所连接的顶点的列表。这可以如下实现。</p> <pre><code class="language-py"># keep vertices in a set vertices = {0, 1, 2, 3, 4, 5} # keep edges in a set edges = {(0, 1), (1, 2), (0, 3), (1, 3), (3, 4), (2, 5), (4, 5), (2, 4)} # create a dictionary with vertices of graph as keys and empty lists as values adjacencyList={} for vertex in vertices: adjacencyList[vertex]=[] # Represent edges in the adjacency List for edge in edges: v1 = edge[0] v2 = edge[1] adjacencyList[v1].append(v2) adjacencyList[v2].append(v1) # if v1 is connected to v2, v2 is also connected to v1 print("The set of vertices of the graph is:") print(vertices) print("The set of edges of the graph is:") print(edges) print("The adjacency List representing the graph is:") print(adjacencyList) </code></pre> <p>输出:</p> <pre><code class="language-py">The set of vertices of the graph is: {0, 1, 2, 3, 4, 5} The set of edges of the graph is: {(0, 1), (2, 4), (1, 2), (3, 4), (0, 3), (4, 5), (2, 5), (1, 3)} The adjacency List representing the graph is: {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} </code></pre> <p>在上面的输出中,我们可以看到每个关键点代表一个顶点,并且每个关键点都与它所连接的顶点列表相关联。这种实现比图邻接矩阵表示更有效。这是因为我们不需要存储不存在的边的值。</p> <h2 id="结论-22">结论</h2> <p>在本文中,我们研究了表示图的理论概念,然后用 python 实现了一个使用邻接矩阵和邻接表表示的图。请继续关注更多内容丰富的文章。快乐学习。</p> <h1 id="python-中的图形操作有简单的例子">Python 中的图形操作[有简单的例子]</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/graph-operations" target="_blank">https://www.askpython.com/python/examples/graph-operations</a></p> </blockquote> <p>在本文中,我们将讨论如何执行不同的图形操作。图是由顶点和边组成的非线性数据结构。它们用于表示城市之间的地图、用户的社交媒体连接以及网页的连接等。</p> <h2 id="处理图形运算">处理图形运算</h2> <p>如果你没有研究过图的实现,你可以考虑阅读这篇关于 Python 中图的<a href="https://www.askpython.com/python/examples/graph-in-python" target="_blank">实现的文章。现在,没有任何进一步的麻烦,让我们在这里开始不同的图形操作。</a></p> <h3 id="1给定邻接表时显示图的顶点">1.给定邻接表时显示图的顶点</h3> <p>考虑下面的图表示例。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5881ab97e34a7a44225b1fb5ded95f10.png" alt="Graph Implementation In Python" loading="lazy"></p> <p>Graph Implementation In Python- Askpython</p> <p>假设我们已经得到了如下图的邻接表表示。</p> <pre><code class="language-py">graph = {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} print("The adjacency List representing the graph is:") print(graph) </code></pre> <p>输出:</p> <pre><code class="language-py">The adjacency List representing the graph is: {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} </code></pre> <p>由于我们知道代表邻接表的<a href="https://www.askpython.com/python/dictionary/python-dictionary-comprehension" target="_blank">字典</a>的键代表图的顶点,我们可以通过使用字典的 keys()方法提取键来显示图的顶点,如下所示。</p> <pre><code class="language-py">graph = {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} print("The adjacency List representing the graph is:") print(graph) vertices=set(graph.keys()) print("The vertices of the graph are:") print(vertices) </code></pre> <p>输出:</p> <pre><code class="language-py">The adjacency List representing the graph is: {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} The vertices of the graph are: {0, 1, 2, 3, 4, 5} </code></pre> <h3 id="2邻接表时显示图的边">2.邻接表时显示图的边</h3> <p>为了显示图的边,我们将遍历图中的每个顶点(u ),然后通过遍历与每个顶点相关联的相邻顶点的列表来查看与顶点 u 相连的每个顶点(v)。对于每个顶点 u 和 v,我们将在边集中添加一个无序对(u,v)。</p> <p>如果一个顶点 v 在 u 的邻接表中,u 也将出现在 v 的邻接表中。由于这个原因,邻接表包含每条边两次。显示一个图的边有点复杂,因为我们只需要显示一条边一次。</p> <p>为了显示边,我们将首先创建一个无序集合{u,v},表示连接顶点 u 到 v 的边。此后,我们将创建一个列表 E,表示包含每个边{u,v}的边。</p> <p>由于这个原因,如果{u,v}已经在我们的边列表中,{v,u}可以从集合中排除,因为{v,u}和{u,v}被认为是相同的。</p> <p>之后,我们将把 E 中的每一对转换成一个表示图的边的元组。这样,我们可以避免重复,并将边表示如下。</p> <pre><code class="language-py">graph = {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} print("The adjacency List representing the graph is:") print(graph) E = list() for u in graph.keys(): for v in graph[u]: edge = {u, v} if edge not in E: E.append(edge) print("The edges of the graph are:") print(E) </code></pre> <p>输出:</p> <pre><code class="language-py">The adjacency List representing the graph is: {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} The edges of the graph are: [{0, 1}, {0, 3}, {1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 4}, {4, 5}] </code></pre> <h3 id="3向图表添加一个顶点">3.向图表添加一个顶点</h3> <p>为了给图添加一个顶点,我们将简单地添加另一个键和一个空列表作为它的关联邻接表到表示图的字典中,如下所示。</p> <pre><code class="language-py">graph = {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} print("The adjacency List representing the graph is:") print(graph) # adding vertex '6' to graph graph.update({6: []}) print("The new vertices of the graph are:") print(set(graph.keys())) </code></pre> <p>输出:</p> <pre><code class="language-py">The adjacency List representing the graph is: {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2]} The new vertices of the graph are: {0, 1, 2, 3, 4, 5, 6} </code></pre> <h3 id="4给图表添加一条边">4.给图表添加一条边</h3> <p>要将边(u,v)添加到图中,我们将首先检查边“u”和“v”是否都出现在图中。如果他们中的任何一个不存在,我们将中止该过程。</p> <p>如果边“u”和“v”都出现在图中,我们将把 u 添加到与 v 相关联的邻接表中,然后我们将把 v 添加到与 u 相关联的邻接表中。</p> <p>这可以如下进行。</p> <pre><code class="language-py">graph = {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2],6:[]} print("The adjacency List representing the graph is:") print(graph) # adding edges (5,6) and (4,6) to graph new_edges = [(5, 6), (4, 6)] for edge in new_edges: u=edge[0] v=edge[1] graph[u].append(v) graph[v].append(u) #display new edges E = list() for u in graph.keys(): for v in graph[u]: edge = {u, v} if edge not in E: E.append(edge) print("The new edges of the graph are:") print(E) </code></pre> <p>输出:</p> <pre><code class="language-py">The adjacency List representing the graph is: {0: [1, 3], 1: [0, 2, 3], 2: [4, 1, 5], 3: [4, 0, 1], 4: [2, 3, 5], 5: [4, 2], 6: []} The new edges of the graph are: [{0, 1}, {0, 3}, {1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 4}, {4, 5}, {4, 6}, {5, 6}] </code></pre> <h2 id="结论-23">结论</h2> <p>在本文中,我们已经看到了如何在图上执行不同的操作,比如向图中添加顶点或边,以及显示图的边和顶点。请继续关注更多内容丰富的文章。</p> <p>快乐学习!</p> <h1 id="使用-python-qt-的-gui-应用程序初学者指南">使用 Python Qt 的 GUI 应用程序——初学者指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/gui-applications-using-python-qt" target="_blank">https://www.askpython.com/python-modules/gui-applications-using-python-qt</a></p> </blockquote> <p>在本文中,我们将学习如何用 Python Qt 开发 GUI 应用程序。没有一个好的用户界面,你就不能指望有一个为大众服务的工具。因此,掌握为应用程序设计简单界面的艺术可以显著加快开发速度。</p> <hr> <h2 id="python-qt-是什么">Python Qt 是什么?</h2> <p>Python Qt 是最流行的图形用户界面开发工具包之一。许多大型科技公司用它来开发桌面应用程序。以下是它的一些主要特性:</p> <ol> <li><strong>跨平台</strong>:这是一个跨平台的软件,所以应用程序可以在任何操作系统上运行。</li> <li><strong>开源:</strong>一个软件开发者可以使用 GitHub 贡献自己的库。许多编程语言支持它的开发。这份名单是: <ol> <li><strong>C/C++</strong></li> <li><strong>Python</strong></li> <li><strong>响铃</strong></li> <li><strong>出发</strong></li> <li><strong>生锈</strong></li> <li><strong>PHP</strong></li> <li><strong>Java</strong></li> </ol> </li> <li><strong>简单易学:</strong>初级水平即可学习,具备开发 GUI 应用的能力。</li> <li><strong>支持工具:</strong>它带有一个 Designer studio,可以帮助创建没有代码的应用程序。</li> </ol> <p>更多详情请访问官方网站:<a href="https://www.qt.io/product/supported-platforms-languages" target="_blank">https://www.qt.io/product/supported-platforms-languages</a></p> <h2 id="pyqt5-是什么">PyQt5 是什么?</h2> <p>PyQt5 是 Qt designer studio for Python 编程语言的扩展。它是 Python 中著名的 GUI 开发 API 之一,包括 Tkinter、Kivy、CherryPy 等。最重要的是,我们可以使用代码和设计工作室开发应用程序,帮助放置小工具而无需编码。参观项目现场:<a href="https://pypi.org/project/PyQt5/" target="_blank">https://pypi.org/project/PyQt5/</a></p> <h3 id="安装说明">安装说明</h3> <p>您需要为您的系统考虑以下规格:</p> <ol> <li><strong>Python: 3.6.x 或以上</strong></li> <li><strong>操作系统:Windows/MAC/Linux</strong></li> <li><strong>IDE/Teext 编辑器:Visual Studio 代码,Vim,PyCharm 等。</strong></li> <li>环境(<em>可选</em>):蟒蛇</li> </ol> <p>打开您的命令提示符或终端,键入下面的 <a href="https://www.askpython.com/python-modules/python-pip" target="_blank">pip 命令</a>。</p> <pre><code class="language-py">pip install PyQt5 </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/859ce51742058a190a11a758fb39e647.png" alt="Installing PyQt5" loading="lazy"></p> <p>Installing PyQt5</p> <hr> <h2 id="使用-python-qt-构建简单的-gui-应用程序">使用 Python Qt 构建简单的 GUI 应用程序</h2> <p>让我们开始使用之前讨论过的 PyQt5 实现一个简单的 GUI 应用程序。</p> <h3 id="1创建基本窗口">1.<strong>创建基本窗口</strong></h3> <pre><code class="language-py"># importing the qtWidgets class from the PyQt5 class from PyQt5 import QtWidgets as qtw # creating a class of the main wndow and inheriting it from the QtWidgets QWidgrt class class MainWindow(qtw.QWidget): def __init__(self): super().__init__() self.setWindowTitle('Hello GUI') self.show() # a method that displays everything on the screen # instance of the QtWidget window app = qtw.QApplication([]) # instance of the MainWindow() class main = MainWindow() # starting the application app.exec_() </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6eac782bc7e69204528dfd2005a42c2d.png" alt="First Display Screen With PyQt5" loading="lazy"></p> <p>First Display Screen With PyQt5</p> <p>代码本身的解释将详细定义每一个元素。任何 Qt app 都有基本的六个要素。</p> <ol> <li>主窗口类:这个类包含了所有的窗口小部件、按钮、文本、显示屏和其他子窗口小部件。我们可以说它是所有子对象的父窗口。</li> <li>这个类是我们在主窗口类中使用的所有<strong>部件</strong>的集合。对于任何应用程序开发,它必须在主类内部继承。</li> <li><strong>self.setWindowTitle():</strong> 这个方法给我们的 app 窗口赋予标题。</li> <li><strong>self.show():</strong> 整个应用从执行到放置和管理的一切都在这个函数的指挥之下。请记住,如果我们不在 MainWindow 类中调用它,那么系统将不会显示,它只会继续在后台运行。</li> <li><strong>QApplication 的实例:</strong>要运行任何 Qt 程序,创建类的对象是非常必要的。QWidget 模块的 QApplication 实例命名为-<strong>app</strong>。</li> <li>MainWindow 的实例: MainWindow 的实例是给我们的应用程序植入新的功能。我们需要几次,但这是强制性的。</li> <li><strong>执行功能:</strong>执行我们 app 的执行。我们将在最后一行代码中调用这个函数。</li> </ol> <p>PyQt5 库中还有几个小部件,它们对于快速 GUI 编程是必不可少的。</p> <ol> <li><strong>框布局:</strong>输出消息框,用于显示任何事件的消息。</li> <li><strong>标签:</strong>为了定义 GUI 应用程序中每个东西的功能,我们使用标签。它们可以帮助用户更容易地与应用程序进行交互。</li> <li><strong>按钮:</strong>Qt 提供了很多类型的按钮,如按钮、单选按钮等。</li> <li><strong>字体:</strong>字体是各种类型的吸引人的字母。字体的主要目的是制作一个有吸引力的用户界面,并提供良好的用户体验。它们是用来装饰课文的。</li> </ol> <p><strong>电子显示(LCD)屏幕:</strong>数字显示增加了应用程序的吸引力。LCD 数字主要用于<strong>计算器或公制转换应用。</strong></p> <hr> <h2 id="安装-qt-designer-studio">安装 Qt Designer Studio</h2> <p>这是一个巨大的库,为我们提供了大量的选项和软件包,使得 GUI 编程变得更加容易。主要好处是它自带内置 <strong>Qt 设计师工作室</strong>。它是一个拖放界面,帮助我们快速开发桌面应用程序。</p> <p>在以前的版本中,设计器内置了库。但是,由于新的开发,它已经成为 PyQt5 的一个单独的包。因此,要将其添加到系统中,请使用以下命令:</p> <ol> <li>打开<strong>命令提示符</strong>,输入 <strong>pip install PyQt5Designer</strong> 。</li> <li>要启动它,只需在命令提示符中键入命令–<strong>‘designer’</strong>。界面看起来是这样的。</li> </ol> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/9533f238697a9c080b327cbd1f24b167.png" alt="The Interface Of Qt Designer Studio" loading="lazy"></p> <p>The interface of Qt Designer Studio</p> <p>这是最简单的操作 GUI 生成器。我们唯一需要做的就是将对象拖放到主窗口中。然后保存这个文件,我们就可以开始编程内部功能了。</p> <p><strong>注意:</strong>设计者只能创建 GUI 应用程序的布局。我们需要通过 Python 代码对应用程序进行显式编程。</p> <h2 id="使用-pyqt5-designer-studio-设计-gui-应用程序">使用 PyQt5 Designer studio 设计 GUI 应用程序</h2> <p>在本节中,我们将创建一个简单的 GUI 应用程序,并使用命令行参数来执行它。这不会是一个可行的方案。这只是一个演示,展示了我们如何创建基本布局,然后将它们更改为脚本。让我们开始吧:</p> <h3 id="1设置主窗口">1.设置主窗口</h3> <p>通过在命令提示符下键入<strong>designer.exe</strong>打开设计器,然后选择窗格打开。它会询问背景窗口的类型。选择<strong>主窗口</strong>选项,它会为我们创建一个空白界面:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/0c58477925ffa298ebee72e2ea513a2a.png" alt="Selection Pane" loading="lazy"></p> <p>Selection Pane</p> <h3 id="2widget-选择框之旅"><strong>2。widget 选择框之旅</strong></h3> <p>小部件选择框位于窗口的左侧。从大到小,有各种类型的小部件可供使用。所以,我们就来看看它们:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8074a22412da67dbc212406fcad5c417.png" alt="The Widget Selection Box" loading="lazy"></p> <p>The widget selection box</p> <p><strong>以下是全部:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/2e9ea19296cba9019268397115f0ce52.png" alt="Screenshot 667" loading="lazy"></p> <p>The basic widgets containing layouts, buttons, view styles and other formatting options.</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/714db12347d9a943c2d86564900997cb.png" alt="Screenshot 669" loading="lazy"></p> <p>Input widgets</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/548ab0f6f1e56d3dd3e93d7361cf2c13.png" alt="Screenshot 668" loading="lazy"></p> <p>Container</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/72c175efdfd18b0aa558cb7e008fece2.png" alt="Screenshot 670" loading="lazy"></p> <p>Display widgets and scratchpad</p> <h3 id="3创建一个简单的按钮应用">3.创建一个简单的按钮应用</h3> <p>按钮是执行单一任务的简单按钮。它可能是登录到一个网站,开始一个进程,启动一个游戏,等等。我们只需要推一把。我们的应用程序的机制很简单。</p> <p>当我们点击它的时候,它会说<strong>点击了!!!。这是初学者尝试构建的常见应用之一,因为它描述了 GUI 的工作方式。</strong></p> <ol> <li>打开设计器,选择背景放置器作为主窗口。</li> <li>在 widget 菜单中选择<strong>按钮</strong>,并将其拖入<strong>主窗口。</strong></li> </ol> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fff35ec25f2c063912fab32a518396ad.png" alt="Push Button GUI Applications Using Python Qt" loading="lazy"></p> <p>Push Button</p> <p>3.右侧是“特性”选项板。我们可以通过它改变每个对象的属性。每个对象都必须有一个唯一的名称。所以,我们把这个按钮命名为 <strong>click_me_button</strong> 。之后,我们通过使用每边的端点拉伸按钮来改变按钮的大小。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5048c46af4ebaed450d4ba46832c2b90.png" alt="Customized Button" loading="lazy"></p> <p>Giving a new name to the button</p> <p>4.然后,我们放置一个标签,然后我们应用相同的变化。字体很小,因此,我们在属性面板中将字体大小改为 <strong>36</strong> 。人们可以探索字体部分,因为它有大量的选项可以修改。我们将标签的文本改为<strong>你好</strong>,按钮改为<strong>点击我</strong>。总的来说,我们的布局是这样的。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f152c218a901dec08a21eb1ee1ce3265.png" alt="Customized Label" loading="lazy"></p> <p>Customized button</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/928907af18a09b128bf137494b2f89ed.png" alt="New Layout Of The App" loading="lazy"></p> <p>New layout of the app</p> <p>现在我们有了一个基本的应用程序。只需将其保存在所需的选择目录中。因此,转到左上角的文件选项,点击<strong>保存</strong>或使用键<strong>‘Ctrl+S’</strong>。我们给它起了个名字 <strong>myui.ui</strong> 。但是,它是一个 <strong><?带有</strong>的 xml >文件。ui"** 扩展。**</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ea0106a80663982e54990fb844e6c720.png" alt="Saving The File" loading="lazy"></p> <p>Saving The File</p> <p>为了执行这个文件,我们需要将它转换成一个 Python 脚本。有一个特殊的转换命令:</p> <pre><code class="language-py">pyuic5 -x app_name.ui -o app_name.py </code></pre> <p>转到命令提示符,输入该命令并按 enter 键。我们可以给 python 脚本取任何名称,但是要确保我们之前保存的 UI 文件的名称应该是正确的,否则命令将会失败。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ffa74bc3bf77b17e7942ed0ceafb1778.png" alt="Command Excution" loading="lazy"></p> <p>Command Execution</p> <p>现在,我们的应用程序有了 Python 脚本,即 my_app.py。记得将它放在与<strong>相同的目录中。ui</strong> 文件存在,这使得未来的任务更加容易。<strong>当我们打开脚本时,它包含了自动生成的全部代码。这就像魔术一样。让我们看看:</strong></p> <p><strong>代码(由系统通过“pyuic5”命令自动创建):</strong></p> <pre><code class="language-py"># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'myui.ui' # # Created by: PyQt5 UI code generator 5.15.6 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(253, 264) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.click_me_button = QtWidgets.QPushButton(self.centralwidget) self.click_me_button.setGeometry(QtCore.QRect(0, 130, 251, 91)) font = QtGui.QFont() font.setPointSize(36) self.click_me_button.setFont(font) self.click_me_button.setObjectName("click_me_button") self.helo_world_label = QtWidgets.QLabel(self.centralwidget) self.helo_world_label.setGeometry(QtCore.QRect(10, 40, 241, 81)) font = QtGui.QFont() font.setPointSize(36) self.helo_world_label.setFont(font) self.helo_world_label.setObjectName("hello_world_label") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 253, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.click_me_button.setText(_translate("MainWindow", "Click Me")) self.helo_world_label.setText(_translate("MainWindow", "Hello!")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre> <p>当我们运行这段代码时,我们得到一个基本的用户界面,它什么也不做。</p> <p><strong>输出</strong>:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3404c504a8185b40ea68d62cc1f61080.png" alt="First Qt Application" loading="lazy"></p> <p>First Qt Application</p> <p>现在,是时候给按钮添加一些动作了。</p> <p>当我们点击那个按钮时,标签会显示一些东西。为了实现它,我们将定义一个函数为 <strong>press_the_button()</strong> 。当有人点击它时,标签会显示<strong>‘你好世界’</strong>,而不仅仅是<strong>‘你好’</strong>。</p> <p><strong>功能代码:</strong></p> <pre><code class="language-py"> # a function that passes a string 'hello world' when we click a button def press_the_button(self): self.hello_world_label.setText('Hello world!') </code></pre> <p>让我们将函数作为 lambda 参数添加。</p> <pre><code class="language-py">self.click_me_button = QtWidgets.QPushButton(self.centralwidget) </code></pre> <p>使用这个 <strong><a href="https://www.askpython.com/python/python-lambda-anonymous-function" target="_blank">匿名函数</a></strong> 的目的是:在声明之前将一个已经存在的函数调用传递给新的小部件,这样 lambda 可以很好地管理它。实现后看起来是这样的:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/354bc42ce90ea53e89a443e0abebc702.png" alt="Placing The Function" loading="lazy"></p> <p>Placing The Function</p> <p>在这之后,我们保存代码并重新启动应用程序,点击按钮,它显示文本:<strong>‘Hello World’。</strong></p> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8c6d72b488a8cafb44dc804c961c142d.png" alt="Before Clicking The Button 1" loading="lazy"></p> <p>Before Clicking The Button</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3b7cb4bcb7071b02f77fa70322a95223.png" alt="After Clicking The Button 1" loading="lazy"></p> <p>After Clicking The Button</p> <p>因此,通过这种方式,我们可以使用 PyQt5 和 Python 进行更改并创建出色的 GUI 应用程序。</p> <h2 id="结论-24">结论</h2> <p>用 Qt 和 Python 开发快速 GUI 应用程序的主题到此结束。这个库非常大,还有许多部分需要理解和实现。因此,我建议读者确保仔细阅读安装过程和后续章节。关于这个话题,还有更多的内容。</p> <h1 id="如何用-python-中的-tkinter-搭建一个-gui-计算器">如何用 Python 中的 Tkinter 搭建一个 GUI 计算器?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/gui-calculator-using-tkinter" target="_blank">https://www.askpython.com/python/examples/gui-calculator-using-tkinter</a></p> </blockquote> <p>在今天的这篇文章中,我们将学习如何使用 Tkinter 创建一个简单的 GUI 计算器。我们将逐步理解整个代码。</p> <h2 id="使用-tkinter-开始使用我们的-gui-计算器">使用 Tkinter 开始使用我们的 GUI 计算器</h2> <p>在我们开始之前,确保您已经为 Python 安装了 <a href="https://www.askpython.com/python-modules/tkinter/tkinter-canvas" target="_blank">Tkinter 库</a>。Tkinter 是 Python 编程语言的标准 GUI 库。当 python 与 Tkinter 合并时,它提供了一种快速简单的方法来创建图形用户界面应用程序。</p> <p>Tkinter 为 Tk GUI 工具包提供了一个强大的面向对象的接口。如果 python 中没有预装 Tkinter,则打开 windows cmd 并输入以下命令。</p> <pre><code class="language-py">pip install python-tk </code></pre> <hr> <h2 id="tkinter-messagebox">Tkinter Messagebox</h2> <p><a href="https://www.askpython.com/python-modules/tkinter/tkinter-messagebox-and-radiobutton" target="_blank">Messagebox</a> 是 Python 的 Tkinter 库中的一个小部件。它用于显示 python 应用程序中的消息框。该模块用于使用一定数量的功能显示消息。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">messagebox.Name_of_the_function(title,message[, options]) </code></pre> <p><strong>参数</strong>:</p> <ul> <li><strong>Function_Name:</strong> 该参数用来表示一个合适的消息框函数。</li> <li><strong>title:</strong> 该参数是一个字符串,显示为消息框的标题。</li> <li><strong>message:</strong> 该参数是在消息框上显示为消息的字符串。</li> <li><strong>选项:</strong>有两个选项可以使用: <ol> <li><strong>默认:</strong>该选项用于指定消息框中的默认按钮,如中止、重试或忽略。</li> <li><strong>parent:</strong> 该选项用于指定消息框显示在哪个窗口的顶部。</li> </ol> </li> </ul> <hr> <h2 id="使用-tkinter-的-gui-计算器的结构">使用 Tkinter 的 GUI 计算器的结构</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/709223858d9a0a2d3b37942161132c19.png" alt="Calculator" loading="lazy"></p> <p><strong>Python Tkinter 标签:</strong>标签用于指定我们可以放置文本或图片的容器框。这个小部件用于向用户提供关于 python 应用程序中使用的其他小部件的消息。</p> <p><strong>Python 框架:</strong>框架只是一种小部件。python 中的框架只不过是其子元素的简单容器。使用这些,我们可以给子容器主机,我们可以一帧一帧地划分整个布局。</p> <p>假设我们运行这个程序,我们在开始有一个标签,然后在根窗口有几个按钮。我们可以把这个根窗口一部分一部分的划分,比如标签作为一个部分,然后按钮分成不同的部分。如果我们把这些部分放在一个框架中,那么这个框架就是一个父元素。这将帮助我们简化复杂的设计。</p> <p>添加框架后,计算器结构将如下所示:</p> <ol> <li>标签</li> <li>框架 1 : 4 个按钮</li> <li>框架 2 : 4 个按钮</li> <li>框架 3 : 4 个按钮</li> <li>框架 4 : 4 个按钮</li> </ol> <p><strong>Python 按钮:</strong>按钮部件用于在 Python 应用程序中添加按钮。这些按钮可以显示传达按钮用途的文本或图像。您可以将一个函数或方法附加到一个按钮上,单击该按钮时会自动调用该函数或方法。</p> <hr> <h3 id="1定义函数">1。定义函数</h3> <p>这里我们将从按钮的编码部分开始。</p> <pre><code class="language-py">val="" A = 0 operator="" def btn_1_isclicked(): global val #Concatinate string value 1 with the val and store it in the variable val again val = val + "1" data.set(val) </code></pre> <p>我们将定义第一个名为 <strong>btn_1_isclicked( )</strong> 的函数。我们给它起了一个精心设计的名字,这样我们通过观察它就能更容易地理解这个函数实际上在做什么。</p> <p>在这里,我们希望每当我们单击任何数字按钮时,我们希望该数字显示在我们的标签上,并将其存储在不同的变量中,以便于计算。</p> <p>我们将接受一个全局变量,以避免变量名问题。在 Python 中,在函数外部或全局范围内声明的变量称为全局变量。</p> <p>这意味着全局变量可以在函数内部或外部访问。这里的 val 是一个全局变量。在上面的代码中,我们创建了 val 作为全局变量,并定义了一个<code>btn_1_isclicked( )</code>来打印全局变量 val 并存储它的值。</p> <p>对所有的<a href="https://www.askpython.com/python-modules/tkinter/tkinter-buttons" target="_blank">t inter 按钮</a>执行相同的步骤。</p> <pre><code class="language-py">#import the necessary libraries import tkinter from tkinter import * from tkinter import messagebox val="" A = 0 operator="" def btn_1_isclicked(): global val val = val + "1" data.set(val) def btn_2_isclicked(): global val val = val + "2" data.set(val) def btn_3_isclicked(): global val val = val + "3" data.set(val) def btn_4_isclicked(): global val val = val + "4" data.set(val) def btn_5_isclicked(): global val val = val + "5" data.set(val) def btn_6_isclicked(): global val val = val + "6" data.set(val) def btn_7_isclicked(): global val val = val + "7" data.set(val) def btn_8_isclicked(): global val val = val + "8" data.set(val) def btn_9_isclicked(): global val val = val + "9" data.set(val) def btn_0_isclicked(): global val val = val + "0" data.set(val) def btn_add_clicked(): global A global operator global val A = int(val) operator = "+" val = val + "+" data.set(val) def btn_sub_clicked(): global A global operator global val A = int(val) operator = "-" val = val + "-" data.set(val) def btn_mul_clicked(): global A global operator global val A = int(val) operator = "*" val = val + "*" data.set(val) def btn_div_clicked(): global A global operator global val A = int(val) operator = "/" val = val + "/" data.set(val) def btn_equal_clicked(): global A global operator global val A = int(val) operator = "=" val = val + "=" data.set(val) def C_pressed(): global A global operator global val val = "" A=0 operator="" data.set(val) def result(): global A global operator global val val2 = val if operator == "+": x=int((val2.split("+")[1])) c = A + x data.set(c) val=str(c) elif operator == "-": x=int((val2.split("-")[1])) c = A - x data.set(c) val=str(c) elif operator == "*": x=int((val2.split("*")[1])) c = A * x data.set(c) val=str(c) elif operator == "/": x=int((val2.split("/")[1])) if x==0: messagebox.show("Error","Division by 0 Not Allowed") A=="" val="" data.set(val) else: c=int(A/x) data.set(c) val=str(c) </code></pre> <h3 id="2使用-tkinter-为我们的-gui-计算器创建窗口">2.使用 Tkinter 为我们的 GUI 计算器创建窗口</h3> <p>为了初始化 tkinter,我们必须创建一个 <a href="https://www.askpython.com/python/tkinter-gui-widgets" target="_blank">Tk root 小部件</a>,这是一个带有标题栏和窗口管理器提供的其他装饰的窗口。</p> <p>根窗口是我们程序中的一个主要应用程序窗口。它有一个标题栏和边框。</p> <p>这些是由窗口管理器提供的。它必须在创建任何其他小部件之前创建。</p> <p><code>geometry</code>方法设置窗口的大小并将其定位在屏幕上。前两个参数是窗口的宽度和高度。最后两个参数是 x 和 y 屏幕坐标。</p> <p>通过将 root.resizable 设置为(0,0),程序员将无法调整窗口的大小。最好使用 root.resizable(0,0 ),因为它会使计算器看起来合适。</p> <pre><code class="language-py">#create a root window root = tkinter.Tk() #set geometry root.geometry("250x400+300+300") #disable the resize option for better UI root.resizable(0,0) #Give the tiltle to your calculator window root.title("AskPython-Cal") </code></pre> <h3 id="3设置标签格式">3.设置标签格式</h3> <p>标签是一个显示框,您可以在其中放置文本或图像。这个小部件显示的文本可以随时更新。也可以给文本的一部分加下划线(就像识别键盘快捷键一样)并将文本跨多行显示。</p> <p>标签的父标签是根标签。这意味着它不会局限于单个框架,而是整个根窗口。然后,我们将放入一个简单的文本,我们将在整个代码中动态地改变它,直到我们单击的数字按钮显示在标签上。</p> <p>Tkinter StringVar 帮助您更有效地管理标签或条目等小部件的值。容器是一个与 <strong>StringVar</strong> 对象相关联的小部件。如果跳过容器,它默认为根窗口,value 是初始值,默认为空字符串。</p> <p><strong>anchor</strong> :如果小工具的空间超过了文本需要的空间,它控制文本的位置。默认值是 anchor=SE(小部件将被放置在框架的右下角)。</p> <p><strong>textvariable :</strong> 为了能够从您的入口小部件中检索当前文本,您必须将该选项设置为 StringVar 类的一个实例,即 data</p> <pre><code class="language-py">#Label data= StringVar() lbl=Label( root, text="Label", anchor=SE, font=("Verdana",20), textvariable=data, background="#ffffff", fg="#000000", ) #expand option deals with the expansion of parent widget. lbl.pack(expand=True,fill="both",) </code></pre> <h3 id="4包装窗户上的纽扣">4.包装窗户上的纽扣</h3> <p>框架是 python 中的一个小部件。这对于以某种友好的方式对其他小部件进行分组和组织是非常重要的。它像一个容器一样工作,负责安排其他小部件的位置。</p> <p>它使用屏幕上的矩形区域来组织布局,并为这些小部件提供填充。</p> <p>框架也可以用作基础类来实现复杂的小部件。</p> <p>我们给 fame 的变量名为 <strong>btnrow1</strong> 。帧的语法是:</p> <pre><code class="language-py">variable_name=Frame(parent_window,options..) </code></pre> <ul> <li>在我们的代码中,root 代表父窗口。</li> <li><strong>选项</strong>——以下是我们代码中最常用的选项列表。这些选项可以用作逗号分隔的键值对。</li> <li><strong>bg</strong> :标签和指示器后面显示的正常背景色。</li> </ul> <p>然后我们包装框架。通过调用根窗口,对其他三个帧重复相同的步骤。</p> <pre><code class="language-py">#Frame Coding for Buttons #Frame for root window #Frame 1 btnrow1=Frame(root,bg="#000000") #If frame gets some space it can expand btnrow1.pack(expand=True,fill="both",) #Frame 2 btnrow2=Frame(root) btnrow2.pack(expand=True,fill="both",) #Frame 3 btnrow3=Frame(root) btnrow3.pack(expand=True,fill="both",) #Frame 4 btnrow4=Frame(root) btnrow4.pack(expand=True,fill="both",) </code></pre> <h3 id="5使用-tkinter-向我们的-gui-计算器添加按钮"><strong>5。使用 Tkinter 向我们的 GUI 计算器添加按钮</strong></h3> <p><a href="https://www.askpython.com/python/tkinter-gui-widgets" target="_blank">按钮小部件</a>用于使用 Python 中的 Tkinter 库在我们的 GUI 计算器中添加按钮。这些按钮可以显示传达按钮用途的文本或图像。您可以将一个函数或方法附加到一个按钮上,单击该按钮时会自动调用该函数或方法。</p> <p><strong>浮雕:</strong>默认值,浮雕=凹槽。您可以将此选项设置为任何其他样式,如:凹陷、刚性、凸起、扁平。</p> <p><strong>命令</strong>是点击按钮时要调用的函数或方法。这里我们调用<strong>命令= btn_1_isclicked,</strong>我们之前创建的执行任务的函数。</p> <p>对于其他按钮,我们也遵循相同的方法。</p> <pre><code class="language-py">#Button row One #Button 1 btn1=Button( btnrow1, text = "1", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_1_isclicked, ) #Buttons will be side by side btn1.pack(side=LEFT,expand=True,fill="both",) #Button 2 btn2=Button( btnrow1, text = "2", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_2_isclicked, ) #Buttons will be side by side btn2.pack(side=LEFT,expand=True,fill="both",) #Button 3 btn3=Button( btnrow1, text = "3", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_3_isclicked, ) #Buttons will be side by side btn3.pack(side=LEFT,expand=True,fill="both",) #Button add btnadd=Button( btnrow1, text = "+", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_add_clicked, ) #Buttons will be side by side btnadd.pack(side=LEFT,expand=True,fill="both",) #Button row Two #Button 4 btn4=Button( btnrow2, text = "4", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_4_isclicked, ) #Buttons will be side by side btn4.pack(side=LEFT,expand=True,fill="both",) #Button 5 btn5=Button( btnrow2, text = "5", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_5_isclicked, ) #Buttons will be side by side btn5.pack(side=LEFT,expand=True,fill="both",) #Button 6 btn6=Button( btnrow2, text = "6", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_6_isclicked, ) #Buttons will be side by side btn6.pack(side=LEFT,expand=True,fill="both",) #Button Subtraction btnsub=Button( btnrow2, text = "-", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_sub_clicked, ) #Buttons will be side by side btnsub.pack(side=LEFT,expand=True,fill="both",) #Button row Three #Button 7 btn7=Button( btnrow3, text = "7", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_7_isclicked, ) #Buttons will be side by side btn7.pack(side=LEFT,expand=True,fill="both",) #Button 8 btn8=Button( btnrow3, text = "8", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_8_isclicked, ) #Buttons will be side by side btn8.pack(side=LEFT,expand=True,fill="both",) #Button 9 btn9=Button( btnrow3, text = "9", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_9_isclicked, ) #Buttons will be side by side btn9.pack(side=LEFT,expand=True,fill="both",) #Button Multiply btnmul=Button( btnrow3, text = "*", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_mul_clicked, ) #Buttons will be side by side btnmul.pack(side=LEFT,expand=True,fill="both",) #Button row Four #Button C btnC=Button( btnrow4, text = "C", font = ("Verdana",22), relief =GROOVE, border=0, command = C_pressed, ) #Buttons will be side by side btnC.pack(side=LEFT,expand=True,fill="both",) #Button 0 btn0=Button( btnrow4, text = "0", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_0_isclicked, ) #Buttons will be side by side btn0.pack(side=LEFT,expand=True,fill="both",) #Button Equal to btnequal=Button( btnrow4, text = "=", font = ("Verdana",22), relief =GROOVE, border=0, command=result, ) #Buttons will be side by side btnequal.pack(side=LEFT,expand=True,fill="both",) #Button Divide btndiv=Button( btnrow4, text = "/", font = ("Verdana",22), relief =GROOVE, border=0, command = btn_div_clicked, ) #Buttons will be side by side btndiv.pack(side=LEFT,expand=True,fill="both",) root.mainloop() </code></pre> <p>最后,我们进入主循环。事件处理从这一点开始。主循环从窗口系统接收事件,并将它们分派给应用程序小部件。当我们点击标题栏的关闭按钮或调用<code>quit()</code>方法时,它被终止。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/211bcf47dba9209460e05c3902373804.png" alt="Cal" loading="lazy"></p> <h2 id="结论-25">结论</h2> <p>在这篇文章中,我们介绍了 Tkinter 按钮、框架、标签及其功能、Tkinter 窗口、输入框以及如何将这些放在一起构建 GUI 应用程序。通过理解这些代码,我们成功地使用 tkinter 库及其小部件构建了一个可工作的 GUI 计算器。希望这篇文章有所帮助。</p> <p>谢谢你,祝你学习愉快!</p> <h1 id="python-tkinter一个简单的电子邮件切片器">Python Tkinter:一个简单的电子邮件切片器</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/tkinter/gui-email-slicer" target="_blank">https://www.askpython.com/python-modules/tkinter/gui-email-slicer</a></p> </blockquote> <p>你好,初学者!今天我们将使用 Python 中的 <a href="https://www.askpython.com/python-modules/tkinter/tkinter-buttons" target="_blank">tkinter 模块构建一个简单的电子邮件切片器。在我们开始这个项目之前,让我们知道什么是电子邮件切片机。</a></p> <h2 id="什么是电子邮件切片机">什么是电子邮件切片机?</h2> <p>电子邮件切片器是一个简单的工具,其中电子邮件地址作为输入和输出提供,应用程序返回用户名和域的电子邮件地址给定。它利用了 Python 的<a href="https://www.askpython.com/python/array/array-slicing-in-python" target="_blank">切片操作。</a></p> <p>同样,在我们开始编写代码之前,让我向您展示一下您最终的输出屏幕将会是什么样子。看看下面的图片。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/28570eb96c0996b014506f9267b99eb4.png" alt="Initial Screen Email Slicer" loading="lazy"></p> <p>Initial Screen Email Slicer</p> <p>看起来很酷,对吧?让我们开始吧!</p> <h2 id="用-python-构建电子邮件切片器">用 Python 构建电子邮件切片器</h2> <p>在构建电子邮件切片器时,让我们首先设计屏幕,然后为按钮的功能声明函数。</p> <h3 id="1设计屏幕">1.设计屏幕</h3> <p>为了设计屏幕,让我们导入<code>Tkinter</code>模块,然后创建一个空白窗口。在这一步,我们还将配置一些更改,如背景颜色和应用程序名称。下面的代码将帮助您做到这一点。</p> <pre><code class="language-py">import tkinter as tk window = tk.Tk() window.geometry("480x440") window.config(bg="#BE361A") window.resizable(width=False,height=False) window.title('Simple Email Slicer') </code></pre> <p>这里我们首先导入模块。然后我们创建了一个窗口,设置窗口尺寸,并使背景颜色橙色(你可以根据自己的喜好定制你的屏幕!).</p> <p>我们确保尺寸总体上保持不变,因此我们将 resizable 属性设置为“False”。我们还将应用程序的标题设置为应用程序的名称。现在,最后但同样重要的是,你需要查看窗口,不是吗?</p> <p>因此,我们运行<code>mainloop</code>函数。结果应该看起来像下面的图片!</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ba1b9d52983eb64603340faa14b90fb8.png" alt="Screen1 Email Slicer" loading="lazy"></p> <p>Screen1 Email Slicer</p> <h3 id="2向我们的窗口添加必要的元素">2.向我们的窗口添加必要的元素</h3> <p>现在,一个重要的部分是在我们的应用程序中添加所有必要的元素。我们对应用程序的要求是:</p> <ol> <li><a href="https://www.askpython.com/python-modules/tkinter/tkinter-frame-and-label" target="_blank">标签</a></li> <li><a href="https://www.askpython.com/python-modules/tkinter/tkinter-entry-widget" target="_blank">输入框</a>(取输入)</li> <li><a href="https://www.askpython.com/python-modules/tkinter/tkinter-buttons" target="_blank">按钮</a></li> <li>文本框(打印输出)</li> </ol> <p>现在让我们首先添加关于应用程序的所有信息。现在你可以随心所欲地改变它。我会根据自己的喜好保留它们。添加所需标签的代码如下所示。</p> <pre><code class="language-py">import tkinter as tk window = tk.Tk() window.geometry("480x440") window.config(bg="#BE361A") window.resizable(width=False,height=False) window.title('Simple Email Slicer') greeting = tk.Label(text="Welcome to A Simple Email Slicer!",font=(12),foreground="white",background="black") Info = tk. Label(text="Enter your email id click the done button!\n The application will extract your username and domain name.",foreground= "white",background="#BE361A",font=(10)) greeting.pack() Info.pack() window.mainloop() </code></pre> <p>添加的行已突出显示,供您参考。显然,标签申报和包装在我们启动窗口之前进行。如果你注意到了,我还做了一些改变,比如前景和背景以及字体大小。还是那句话,你可以根据自己的要求选择所有的改动。新的结果如下:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/19ec16ee3109e5462ae85223595d016c.png" alt="Screen2 Email Slicer" loading="lazy"></p> <p>Screen2 Email Slicer</p> <p>就像我们添加标签一样,我们将添加按钮以及输入框。到目前为止,我猜你对这些都很熟悉了。所以我现在将向你展示整个设计代码!</p> <pre><code class="language-py">import tkinter as tk window = tk.Tk() window.geometry("480x440") window.config(bg="#BE361A") window.resizable(width=False,height=False) window.title('Simple Email Slicer') # All the Labels greeting = tk.Label(text="Welcome to A Simple Email Slicer!",font=(12),foreground="white",background="black") Info = tk. Label(foreground= "white",background="#BE361A",font=(10),text="Enter your email id click the done button!\n The application will extract your username and domain name.") entry_label = tk.Label(foreground= "white",font=(10),background="black",text="Enter Your Email Id: ") result_label = tk.Label(font=(10),foreground= "white",background="black",text="The results are as follows:") empty_label0=tk.Label(background="#BE361A") empty_label1=tk.Label(background="#BE361A") empty_label2=tk.Label(background="#BE361A") empty_label3=tk.Label(background="#BE361A") empty_label4=tk.Label(background="#BE361A") empty_label5=tk.Label(background="#BE361A") #The Entry box entry = tk.Entry(font=(11),width=50,justify='center') #The two Buttons button = tk.Button(text="Done!",font=(11)) reset=tk.Button(text="Reset!",font=(11)) #Result text_box = tk.Text(height=5,width=50) #Packing Everything Together empty_label0.pack() greeting.pack() Info.pack() empty_label1.pack() entry_label.pack() empty_label4.pack() entry.pack() empty_label2.pack() button.pack() empty_label5.pack() reset.pack() empty_label3.pack() result_label.pack() text_box.pack() window.mainloop() </code></pre> <p>现在你可能已经注意到定义了一些空标签,它们看起来很没用,但是当我们使用<code>pack</code>而不是<code>place</code>放置元素时,它们有助于在各种元素之间添加换行符(需要 x 和 y 坐标)。现在让我向你展示我们最终的屏幕是什么样的!</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/414cbb80f499ebad3d8b0e34263654b3.png" alt="Complete Design Email Slicer" loading="lazy"></p> <p>Complete Design Email Slicer</p> <p>所以现在我们已经完成了设计,现在按钮什么也没做。为此,我们将在代码中添加一些额外的函数和变量。</p> <h3 id="3向按钮添加功能">3.向按钮添加功能</h3> <p>在直接跳转到按钮之前,我们需要一个地方来存储我们的电子邮件地址,所以我们创建了一个<strong>‘字符串变量’</strong>来存储在输入框中输入的任何内容。我们利用<code>StringVar</code>并将名为<code>textvariable</code>的属性添加到我们创建的输入框中。我只是给你看你需要改变的部分。</p> <pre><code class="language-py">e1=tk.StringVar() entry = tk.Entry(font=(11),width=50,justify='center',textvariable=e1) </code></pre> <h3 id="功能-1获取用户名和域名">功能 1:获取用户名和域名</h3> <p>现在,电子邮件地址的存储已经完成!我们也将为这两个按钮创建两个函数。第一个函数将从我们之前创建的变量 e1 获取电子邮件地址,然后对电子邮件地址使用<code>stripping</code>操作,以便提取用户名和域。</p> <p>执行相同操作的代码如下所示。</p> <pre><code class="language-py">def result(): try: email=entry.get() inp_email = email.strip() username = inp_email[0:inp_email.index('@')] domain = inp_email[inp_email.index('@') + 1:] text_box.delete('1.0', tk.END) msg = 'Email entered was: {}\nYour email username is {}\nAnd your email domain server is {}' msg_formatted = msg.format(email,username,domain) text_box.insert(tk.END,msg_formatted) entry.delete(0, 'end') except: text_box.delete('1.0', tk.END) text_box.insert(tk.END,"ERROR!") </code></pre> <p>现在,问题是<strong>‘为什么我在这里使用了 <a href="https://www.askpython.com/python/python-exception-handling" target="_blank">try-except 块</a>’</strong></p> <p>原因是,如果一个人没有输入有效的电子邮件地址,代码可能会导致一系列未处理的错误,甚至用户也不会意识到应用程序有什么问题。</p> <p>因此,为了避免这种情况,我们确保如果用户输入一个无效的电子邮件 id,那么 except block 将打印<strong>Error</strong>消息。</p> <p>现在操作非常简单。<code>get</code> email 来自输入框变量,<code>strip</code>该字符串删除所有的空格(如果有的话)。</p> <p>现在得到用户名<code>slice</code>字符串,直到我们到达 <strong>'@'</strong> 符号,其余的(不包括@符号)进入域名。</p> <p>现在最后一个操作是利用我们已经创建的<strong>文本框</strong>。为了安全起见,我们删除了文本框中的所有内容(如果有的话),然后插入一条消息,告诉用户找到的域名和用户名。我们还将确保输入框对于下一次输入是干净的。如果发现任何无效条目,运行<code>except</code>块,并打印<strong>‘错误’</strong>消息。</p> <h3 id="功能-2重置应用程序">功能 2:重置应用程序</h3> <p>第一个函数成功完成后,重置函数就变得非常简单了。reset 函数所做的只是清理文本框和输入框。相同的代码如下所示。</p> <pre><code class="language-py">def reset_all(): text_box.delete('1.0', tk.END) entry.delete(0, 'end') </code></pre> <p><strong>但是按键还不行!为什么?</strong>因为我们没有在按钮定义中添加功能。基本上,您需要做的就是将名为<code>command</code>的属性添加到按钮定义中。下面的代码显示相同的内容。</p> <pre><code class="language-py">button = tk.Button(text="Done!",command=result,font=(11)) reset=tk.Button(text="Reset!",command=reset_all,font=(11)) </code></pre> <p>厉害!现在我们已经准备好运行我们的应用程序了!</p> <h2 id="最终的代码和输出">最终的代码和输出</h2> <pre><code class="language-py">import tkinter as tk window = tk.Tk() window.geometry("480x440") window.config(bg="#BE361A") window.resizable(width=False,height=False) window.title('Simple Email Slicer') def result(): try: email=entry.get() inp_email = email.strip() username = inp_email[0:inp_email.index('@')] domain = inp_email[inp_email.index('@') + 1:] text_box.delete('1.0', tk.END) msg = 'Email entered was: {}\nYour email username is {}\nAnd your email domain server is {}' msg_formatted = msg.format(email,username,domain) text_box.insert(tk.END,msg_formatted) entry.delete(0, 'end') except: text_box.delete('1.0', tk.END) text_box.insert(tk.END,"ERROR!") def reset_all(): text_box.delete('1.0', tk.END) entry.delete(0, 'end') # Labels greeting = tk.Label(text="Welcome to A Simple Email Slicer!",font=(12),foreground="white",background="black") Info = tk. Label(foreground= "white",background="#BE361A",font=(10),text="Enter your email id click the done button!\n The application will extract your username and domain name.") entry_label = tk.Label(foreground= "white",font=(10),background="black",text="Enter Your Email Id: ") result_label = tk.Label(font=(10),foreground= "white",background="black",text="The results are as follows:") empty_label0=tk.Label(background="#BE361A") empty_label1=tk.Label(background="#BE361A") empty_label2=tk.Label(background="#BE361A") empty_label3=tk.Label(background="#BE361A") empty_label4=tk.Label(background="#BE361A") empty_label5=tk.Label(background="#BE361A") #Entry e1=tk.StringVar() entry = tk.Entry(font=(11),width=50,justify='center',textvariable=e1) #Buttons button = tk.Button(text="Done!",command=result,font=(11)) reset=tk.Button(text="Reset!",command=reset_all,font=(11)) #Result text_box = tk.Text(height=5,width=50) #Packing Everything Together empty_label0.pack() greeting.pack() Info.pack() empty_label1.pack() entry_label.pack() empty_label4.pack() entry.pack() empty_label2.pack() button.pack() empty_label5.pack() reset.pack() empty_label3.pack() result_label.pack() text_box.pack() window.mainloop() </code></pre> <p>下图显示了代码在一个示例电子邮件地址上运行时的输出。自己用各种电子邮件地址测试一下吧!</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c13d62e14d9ec7a655ec2227412e05b5.png" alt="Output Email Slicer" loading="lazy"></p> <p>Output Email Slicer</p> <h2 id="结论-26">结论</h2> <p>恭喜你!你已经成功地学会了如何自己实现一个简单的电子邮件切片器!希望你学到了一些东西!编码快乐!</p> <h1 id="python--tkintergui-中的天气应用程序">Python | Tkinter–GUI 中的天气应用程序</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/gui-weather-app-in-python" target="_blank">https://www.askpython.com/python/examples/gui-weather-app-in-python</a></p> </blockquote> <p>在本教程中,您将了解如何用 Python 创建 GUI 天气应用程序。它使用开放的天气地图 API 来获取全球城市和地方的最新天气信息。此外,我们将使用 GUI(图形用户界面)而不是传统的枯燥方式来实现天气应用程序,这种方式广泛可用,在 CLI(命令行界面)中显示输出。</p> <h2 id="python-中天气应用程序的代码gui">Python 中天气应用程序的代码–GUI</h2> <p>事不宜迟,让我们直接进入用 Python 创建 GUI 天气应用程序的代码设置</p> <h3 id="1安装并导入-tkinter">1.安装并导入 Tkinter</h3> <p>我们从使用 <a href="https://www.askpython.com/python-modules/python-pip" target="_blank">pip 包管理器</a>安装所需的库开始。在命令行或终端中输入以下命令来安装模块。</p> <p>我们需要安装:</p> <ul> <li><a href="https://www.askpython.com/python-modules/requests-in-python" target="_blank">请求</a>:从 API 获取数据</li> <li>使我们的天气应用程序 GUI(图形用户界面)基于。</li> <li><a href="https://www.askpython.com/python-modules/python-datetime-module" target="_blank">DateTime</a> :将时间从 API 转换为不同的格式</li> </ul> <pre><code class="language-py">pip install tkinter pip install datetime pip install requests pip install json </code></pre> <p>在从终端安装了所需的库之后,我们现在转移到 Python 文件来编码。我们首先将库导入为:</p> <pre><code class="language-py">from tkinter import * import requests import json from datetime import datetime </code></pre> <h3 id="2初始化-tkinter-窗口">2.初始化 Tkinter 窗口</h3> <p>下一步,我们使用 Tkinter 模块初始化 GUI 窗口。</p> <pre><code class="language-py">#Initialize Window root =Tk() root.geometry("400x400") #size of the window by default root.resizable(0,0) #to make the window size fixed #title of our window root.title("Weather App - AskPython.com") </code></pre> <h3 id="3-openweathermap-api">3. OpenWeatherMap API</h3> <p>在我们的代码中,我们将使用开放的天气 API(免费层)来获取准确的最新天气信息。</p> <ul> <li>为此,请访问 <a href="https://openweathermap.org/" target="_blank">OpenWeatherMap</a> 网站,然后<strong>创建</strong>一个账户。</li> <li>创建您的帐户后,转到个人资料,然后“<strong>我的 API 密钥</strong>”。</li> <li>这将为您的 API <strong>键</strong>打开一个网页,如下图所示,复制它以便在下一步的代码中使用。</li> </ul> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8402099b047432b7559bd8a0ed2d36b0.png" alt="Open Weather Api" loading="lazy"></p> <p>Open Weather Map API</p> <h3 id="4天气功能">4.天气功能</h3> <p>接下来,我们将向代码中添加功能。这一部分对于获取正确的天气信息至关重要,因为这涉及到从 API 获取数据并以准确的格式显示出来。</p> <p>我们编写了这个代码的最重要的功能,它用于显示天气,我们在代码中这样做:</p> <pre><code class="language-py">city_value = StringVar() def showWeather(): #Enter you api key, copies from the OpenWeatherMap dashboard api_key = "eda2b2s6d#sd65f4de7c4b8" #sample API # Get city name from user from the input field (later in the code) city_name=city_value.get() # API url weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key # Get the response from fetched url response = requests.get(weather_url) # changing response from json to python readable weather_info = response.json() tfield.delete("1.0", "end") #to clear the text field for every new output #as per API documentation, if the cod is 200, it means that weather data was successfully fetched if weather_info['cod'] == 200: kelvin = 273 # value of kelvin #-----------Storing the fetched values of weather of a city temp = int(weather_info['main']['temp'] - kelvin) #converting default kelvin value to Celcius feels_like_temp = int(weather_info['main']['feels_like'] - kelvin) pressure = weather_info['main']['pressure'] humidity = weather_info['main']['humidity'] wind_speed = weather_info['wind']['speed'] * 3.6 sunrise = weather_info['sys']['sunrise'] sunset = weather_info['sys']['sunset'] timezone = weather_info['timezone'] cloudy = weather_info['clouds']['all'] description = weather_info['weather'][0]['description'] sunrise_time = time_format_for_location(sunrise + timezone) sunset_time = time_format_for_location(sunset + timezone) #assigning Values to our weather varaible, to display as output weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}" else: weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!" tfield.insert(INSERT, weather) #to insert or send value in our Text Field to display output </code></pre> <p>作为添加功能的最后一步,我们添加了一个函数来改变时间格式,这个函数检查本地时间与 UTC( <strong>世界协调时间</strong>)的对比,在 UTC 中,API 根据我们的位置给出时间格式的输出。《出埃及记》世界协调时呼叫 IST。</p> <pre><code class="language-py">def time_format_for_location(utc_with_tz): local_time = datetime.utcfromtimestamp(utc_with_tz) return local_time.time() </code></pre> <h3 id="5编写-gui-代码前端元素">5.编写 GUI 代码(前端元素)</h3> <p>我们现在开始按照 GUI 对元素进行编码,包括标题、文本、标签、按钮等。</p> <p>首先,我们将<strong>文本字段</strong>编码为我们想要天气的<strong>城市名称</strong>,并附上标签来表明这一点:</p> <ul> <li>我们使用 <strong><a href="https://www.askpython.com/python-modules/tkinter/tkinter-frame-and-label" target="_blank">Label</a></strong> 的方法生成一个文本标签来表示城市名称输入字段的用途。</li> <li><strong><a href="https://www.askpython.com/python-modules/tkinter/tkinter-entry-widget" target="_blank">录入</a></strong> 方法用于制作一个录入字段,用于输入城市名称,查看其天气情况。</li> <li>textvaraible 小部件用于在名为 city_value 的变量中存储输入的值</li> <li>除了这些小部件,我们还在代码中应用了一些样式,比如字体大小、颜色等等。</li> </ul> <pre><code class="language-py">city_head= Label(root, text = 'Enter City Name', font = 'Arial 12 bold').pack(pady=10) #to generate label heading inp_city = Entry(root, textvariable = city_value, width = 24, font='Arial 14 bold').pack() #entry field </code></pre> <p>我们编写了一个<strong>查看天气按钮</strong>,点击它可以查看用户输入城市的天气:</p> <ul> <li>我们给我们的按钮一些样式,以及名称——“检查天气”。我们使用' <strong>command</strong> '小部件,它显示了单击(按键)按钮时将运行什么函数(这里是 <strong>showWeather</strong> 函数),如前一步中编码的那样。</li> </ul> <pre><code class="language-py">Button(root, command = showWeather, text = "Check Weather", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20) </code></pre> <p>添加这些内容后,我们在代码中添加输出元素。显示天气信息的元素。</p> <ul> <li>同样,我们在下面的文本框中添加了一个标签作为结果的标题</li> <li>为了显示输出,我们使用了一个<strong>文本字段</strong> ,它在每次按下“检查天气”按钮时获取其值。这个函数用于检查处理后从 API 获取的天气信息,showWeather 函数的输出]</li> </ul> <pre><code class="language-py">weather_now = Label(root, text = "The Weather is: ", font = 'arial 12 bold').pack(pady=10) tfield = Text(root, width=46, height=10) tfield.pack() </code></pre> <p>在执行我们的代码时,Tkinter 显示如下输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/36a357bb7c0b4fb590fabc2a83816290.png" alt="Weather App Frontend In Python" loading="lazy"></p> <p>Weather App Frontend In Python</p> <h2 id="python-中-gui-天气应用程序的最终代码">Python 中 GUI 天气应用程序的最终代码</h2> <pre><code class="language-py">from tkinter import * import requests import json from datetime import datetime #Initialize Window root =Tk() root.geometry("400x400") #size of the window by default root.resizable(0,0) #to make the window size fixed #title of our window root.title("Weather App - AskPython.com") # ----------------------Functions to fetch and display weather info city_value = StringVar() def time_format_for_location(utc_with_tz): local_time = datetime.utcfromtimestamp(utc_with_tz) return local_time.time() city_value = StringVar() def showWeather(): #Enter you api key, copies from the OpenWeatherMap dashboard api_key = "eda2b2s6d#sd65f4de7c4b8" #sample API # Get city name from user from the input field (later in the code) city_name=city_value.get() # API url weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key # Get the response from fetched url response = requests.get(weather_url) # changing response from json to python readable weather_info = response.json() tfield.delete("1.0", "end") #to clear the text field for every new output #as per API documentation, if the cod is 200, it means that weather data was successfully fetched if weather_info['cod'] == 200: kelvin = 273 # value of kelvin #-----------Storing the fetched values of weather of a city temp = int(weather_info['main']['temp'] - kelvin) #converting default kelvin value to Celcius feels_like_temp = int(weather_info['main']['feels_like'] - kelvin) pressure = weather_info['main']['pressure'] humidity = weather_info['main']['humidity'] wind_speed = weather_info['wind']['speed'] * 3.6 sunrise = weather_info['sys']['sunrise'] sunset = weather_info['sys']['sunset'] timezone = weather_info['timezone'] cloudy = weather_info['clouds']['all'] description = weather_info['weather'][0]['description'] sunrise_time = time_format_for_location(sunrise + timezone) sunset_time = time_format_for_location(sunset + timezone) #assigning Values to our weather varaible, to display as output weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}" else: weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!" tfield.insert(INSERT, weather) #to insert or send value in our Text Field to display output #------------------------------Frontend part of code - Interface city_head= Label(root, text = 'Enter City Name', font = 'Arial 12 bold').pack(pady=10) #to generate label heading inp_city = Entry(root, textvariable = city_value, width = 24, font='Arial 14 bold').pack() Button(root, command = showWeather, text = "Check Weather", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20) #to show output weather_now = Label(root, text = "The Weather is:", font = 'arial 12 bold').pack(pady=10) tfield = Text(root, width=46, height=10) tfield.pack() root.mainloop() </code></pre> <p>基于 GUI 的天气应用程序的输出如下所示:</p> <p><a href="https://www.askpython.com/wp-content/uploads/2022/01/Output-for-Weather-app-in-Python.mp4" target="_blank">https://www.askpython.com/wp-content/uploads/2022/01/Output-for-Weather-app-in-Python.mp4</a></p> <h2 id="结论-27">结论</h2> <p>教程到此为止。希望你已经很好地学习了如何用 Python 制作一个天气应用程序,并通过编写一个基于接口的脚本以及 API 调用(打开天气地图)和 Tkinter 来提高水平。</p> <h1 id="python-how-to在-python-中使用-gzip-模块">Python how to——在 Python 中使用 gzip 模块</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/gzip-module-in-python" target="_blank">https://www.askpython.com/python-modules/gzip-module-in-python</a></p> </blockquote> <p>大家好!在今天的文章中,我们将看看 Python 中的 <em>gzip</em> 模块。</p> <p>这个模块给了我们一个简单的方法来处理 gzip 文件(<code>.gz</code>)。这与 Linux 实用程序命令<code>gzip</code>和<code>gunzip</code>非常相似。</p> <p>让我们通过一些说明性的例子来看看如何有效地使用这个模块!</p> <hr> <h2 id="在-python-中使用-gzip-模块">在 Python 中使用 gzip 模块</h2> <p>该模块为我们提供了<code>open()</code>、<code>compress()</code>、<code>decompress()</code>等高级函数,用于快速处理这些文件扩展名。</p> <p>本质上,这将只是打开一个文件!</p> <p>要导入此模块,您需要以下语句:</p> <pre><code class="language-py">import gzip </code></pre> <p>没有必要 <a href="https://www.askpython.com/python-modules/python-pip" target="_blank">pip 安装</a>这个模块,因为它是标准库的一部分!让我们开始处理一些 gzip 文件。</p> <h2 id="写入压缩文件">写入压缩文件</h2> <p>我们可以用<code>gzip.open()</code>的方法直接打开<code>.gz</code>文件,写入这些压缩文件!</p> <pre><code class="language-py">import gzip import os import io name = 'sample.txt.gz' with gzip.open(name, 'wb') as output: # We cannot directly write Python objects like strings! # We must first convert them into a bytes format using io.BytesIO() and then write it with io.TextIOWrapper(output, encoding='utf-8') as encode: encode.write('This is a sample text') # Let's print the updated file stats now print(f"The file {name} now contains {os.stat(name).st_size} bytes") </code></pre> <p>这里注意,我们不能像写字符串一样直接写 Python 对象!</p> <p>我们必须首先使用<code>io.TextIOWrapper()</code>将它们转换成字节格式,然后使用这个包装函数编写它。这就是为什么我们以二进制写模式(<code>wb</code>)打开文件。</p> <p>如果你运行这个程序,你会得到下面的输出。</p> <p><strong>输出</strong></p> <pre><code class="language-py">The file sample.txt.gz now contains 57 bytes </code></pre> <p>此外,您会发现文件<code>sample.txt.gz</code>是在当前目录下创建的。好了,我们已经成功地写入了这个压缩文件。</p> <p>让我们现在尝试解压缩它,并阅读它的内容。</p> <h2 id="从-gzip-文件中读取压缩数据">从 gzip 文件中读取压缩数据</h2> <p>现在,类似于通过包装的<code>write()</code>函数,我们也可以使用相同的函数<code>read()</code>。</p> <pre><code class="language-py">import gzip import os import io name = 'sample.txt.gz' with gzip.open(name, 'rb') as ip: with io.TextIOWrapper(ip, encoding='utf-8') as decoder: # Let's read the content using read() content = decoder.read() print(content) </code></pre> <p><strong>输出</strong></p> <pre><code class="language-py">This is a sample text </code></pre> <p>事实上,我们能够得到我们最初写的相同的文本!</p> <h2 id="压缩数据">压缩数据</h2> <p>这个模块的另一个有用的特性是我们可以使用<code>gzip</code>有效地压缩数据。</p> <p>如果我们有很多字节内容作为输入,我们可以使用<code>gzip.compress()</code>函数来压缩它。</p> <pre><code class="language-py">import gzip ip = b"This is a large wall of text. This is also from AskPython" out = gzip.compress(ip) </code></pre> <p>在这种情况下,将使用<code>gzip.compress</code>压缩二进制字符串。</p> <hr> <h2 id="结论-28">结论</h2> <p>在本文中,我们学习了如何使用 Python 中的 gzip 模块来读写<code>.gz</code>文件。</p> <h2 id="参考-4">参考</h2> <ul> <li>Python gzip 模块<a href="https://docs.python.org/3/library/gzip.html" target="_blank">文档</a></li> <li>关于 Python gzip 模块的 JournalDev 文章</li> </ul> <hr> <h1 id="黑客新闻克隆django-项目创意">黑客新闻克隆——Django 项目创意</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/django/hacker-news-clone-django" target="_blank">https://www.askpython.com/django/hacker-news-clone-django</a></p> </blockquote> <p>在本教程中,我们将使用 <a href="https://www.askpython.com/django" target="_blank">Django Web 框架</a>构建一个<strong>完整的 Web 应用</strong>——类似于黑客新闻网站。如果你想创建一个完整的网站,这是一个很好的 Django 项目想法。学习任何框架都没有比自己开发更好的方法了。</p> <h2 id="关于黑客新闻">关于黑客新闻</h2> <p>Hacker News 是一家社交新闻网站,由投资基金和初创企业孵化器 Y-Combinator 运营和管理。该网站主要关注计算机科学和企业家精神。</p> <p>该网站将自己定义为一个平台,在这里人们可以分享任何“满足自己求知欲”的东西。</p> <p>看看这里的网站—<a href="https://news.ycombinator.com/" target="_blank">黑客新闻</a></p> <p>我们将制作一个包含网站所有主要功能的 web 应用程序。说够了;现在让我们深入研究一下吧!!</p> <h2 id="该网站的一些有趣的特点">该网站的一些有趣的特点</h2> <p>现在我们将看到使用 Django 创建的网站的有趣特性</p> <h3 id="1顶部导航栏">1.顶部导航栏</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8bb0f101207ab6f5332dce54d6280dc5.png" alt="NavBar" loading="lazy"></p> <p>HackerNews NavBar</p> <ul> <li><strong>黑客新闻</strong>按钮带你回到主页。</li> <li><strong>新</strong>按钮显示所有最新的提交。</li> <li><strong>过去</strong>按钮显示的是 <strong>30 分钟</strong>之前提交的内容。</li> <li>同样,还有<strong>问、秀、****工作岗位</strong>不那么重要。</li> <li>然后有一个<strong>提交</strong>选项和一个<strong>注销/登录</strong>选项</li> </ul> <p>我们将在我们的应用程序中编码所有这些。</p> <h3 id="2个人以及职位列表">2.个人以及职位列表</h3> <p>然后我们有一个显示在主页上的帖子列表。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e72d6fe5511ea5c35034a9f69a1171cd.png" alt="List Of Posts " loading="lazy"></p> <p>List Of Posts</p> <ul> <li>每个帖子都有一个<strong>向上投票</strong>选项来投票</li> <li>每个帖子都显示了对它们的<strong>总投票</strong>和<strong>总评论</strong></li> <li>显示创建者的<strong>用户名</strong></li> <li>显示<strong>提交时间</strong></li> </ul> <p>此外,当您点击评论时,网站会将您重定向到评论页面:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/06ad73a549d3e7260cd4db8b4c14939b.png" alt="Post" loading="lazy"></p> <p>Post</p> <p>我们可以在这里发表评论,也可以回复别人。</p> <p>这里一个有趣的特性是形成<strong>线程注释</strong>。</p> <p>那是我们回复评论的时候;我们的回复应该显示在它的正下方。这并不像听起来那么简单,不要担心,我们将在接下来的章节中讨论这个问题。</p> <h3 id="3用户认证">3.用户认证</h3> <p>一个更重要的特性是用户认证。在网站上,我们只有拥有账号才能<strong>发帖、</strong>评论、**** 或<strong>回复</strong>。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/764af1110ef5ca879af792010b217b60.png" alt="Signin" loading="lazy"></p> <p>Signin</p> <p>和注册视图</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c99cc8382faaf675e0e34e71aa7ea6ce.png" alt="Sign Up" loading="lazy"></p> <p>Sign Up</p> <p>我们将再次在代码中包含这两个视图!!</p> <h3 id="4提交后视图">4.提交后视图</h3> <p>该网站有一个提交视图:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/98f00c70a94218c853e7ad12db919b11.png" alt="Submit" loading="lazy"></p> <p>Submit</p> <p>在这里,我们可以提交帖子的<strong>标题、URL、</strong>和<strong>描述</strong>。就这样了,伙计们!!这是我们必须做的。所以让我们开始吧!!</p> <h2 id="在-django-web-应用程序中编写黑客新闻克隆">在 Django Web 应用程序中编写黑客新闻克隆</h2> <p>首先,我们必须<a href="https://www.askpython.com/django/django-app-structure-project-structure" target="_blank">创建一个新的 Django 项目</a>。所以让我们开始吧:</p> <pre><code class="language-py">django-admin startproject HackerNews </code></pre> <p>另外,创建 Django 应用程序。我已经把我的名字命名为—<strong>hnapp</strong>。所以代码应该是:</p> <pre><code class="language-py">django-admin startapp hnapp </code></pre> <p>很好。不要忘记在 settings.py 文件中添加<strong>应用名称</strong>。此外,我们将使用<a href="https://www.askpython.com/django/django-template-inheritance" target="_blank">模板继承</a>来编码我们的模板。</p> <p>在 Django HackerNews 项目目录中创建一个 <strong>templates</strong> 文件夹,并在 settings.py 文件中提到它的路径。</p> <p>我们通过在 TEMPLATES/settings.py 中添加下面一行来实现</p> <pre><code class="language-py">'DIRS': [os.path.join(BASE_DIR,'HackerNews/templates')], </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/dbc1c8c53f4717961e9b85f1c088edb7.png" alt="Templates" loading="lazy"></p> <p>Templates</p> <p>好的,酷,现在添加<strong>base.html</strong>——我们网站的基本模板,在创建的模板文件夹中:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/74fa6d3f2b67f3687762da010f146734.png" alt="Base" loading="lazy"></p> <p>Base</p> <p>在文件中,添加代码:</p> <pre><code class="language-py"><!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> body { margin: 0; font-family: Arial, Helvetica, sans-serif; } .topnav { overflow: hidden; background-color: #333; } .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .topnav a.active { background-color: #FF0000; color: white; } .topnav-right { float: right; } p.ex1 { padding-left: 40px; } </style> </head> <body> {% block content %} {% endblock %} </body> </html> </code></pre> <p>这段代码是为了我们的 web 应用程序的美观。我已经尝试添加 CSS,使它看起来比默认布局更好。</p> <p>同样在<strong>项目/urls.py</strong> 中添加一行:</p> <pre><code class="language-py">from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('hnapp.urls')), ] </code></pre> <p>有了这些,现在让我们开始真正的姜戈部分。</p> <h2 id="1编码所需的模型">1.编码所需的模型</h2> <p>对于网站,我们需要 <strong>:</strong></p> <ul> <li><strong>岗位模型</strong>:存储岗位信息</li> <li><strong>投票模型</strong>:存储每个帖子的 Upvotes</li> <li><strong>评论模型</strong>:存储每篇文章的评论。</li> </ul> <p>以及预先构建的<strong>用户模型</strong>来存储用户账户信息。所以在 <strong>models.py</strong> 中添加了以下型号:</p> <p><strong>岗位型号:</strong></p> <pre><code class="language-py">class Post(models.Model): title = models.CharField("HeadLine", max_length=256, unique=True) creator = models.ForeignKey(User, on_delete= models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) url = models.URLField("URL", max_length=256,blank=True) description = models.TextField("Description", blank=True) votes = models.IntegerField(null=True) comments = models.IntegerField(null=True) def __unicode__(self): return self.title def count_votes(self): self.votes = Vote.objects.filter(post = self).count() def count_comments(self): self.comments = Comment.objects.filter(post = self).count() </code></pre> <p>这里,我们有两个函数来统计每个帖子的总投票数和总评论数。<strong>注意</strong>当创建者删除他的账户时,帖子不应该被删除,因此设置 <strong>on_delete</strong> 到 <strong>models。SET_NULL。</strong></p> <p><strong>投票模式:</strong></p> <pre><code class="language-py">class Vote(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __unicode__(self): return f"{self.user.username} upvoted {self.link.title}" </code></pre> <p>这个模型将存储关于哪个<strong>用户</strong>投票赞成哪个<strong>帖子</strong>的信息。</p> <p><strong>和最终评论模式:</strong></p> <pre><code class="language-py">class Comment(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() identifier = models.IntegerField() parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True) def __unicode__(self): return f"Comment by {self.user.username}" </code></pre> <p>每个评论都会有一个<strong>创建者</strong>,创建者评论的<strong>帖子</strong>,以及<strong>评论内容</strong>本身。</p> <p>现在,每个<strong>回复评论</strong>也将有一个父评论,即回复所针对的评论。因此我们需要一个父字段,它是<strong>评论模型</strong>本身的外键</p> <p>我们还需要另一个字段,一个<strong>标识符字段,</strong>来标识不同级别的回复评论。为了理解这一点,考虑下面的图像:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/118e9f853f0fcf1b1d10695f8db26b66.png" alt="Comment Threads" loading="lazy"></p> <p>Comment Threads</p> <p>因此,</p> <ul> <li>对帖子本身的评论将有<strong>标识符= 0 和 parent = None</strong> ,因为它们是最上面的评论。</li> <li>第一级的回复评论将具有<strong>标识符= 1</strong> ,并且给予回复的评论作为<strong>父评论(标识符=0)</strong></li> <li>类似地,第二层上的回复评论将具有标识符= 2 的<strong>标识符和标识符= 1 的</strong>父评论。****</li> </ul> <p>我们将在后面看到,我们将如何使用这两个字段以线程方式显示注释。</p> <p>这就是模型,现在使用<strong>admin . site . register(model _ name)</strong>行在 <strong>admin.py</strong> 中注册三个模型。</p> <p>另外,不要忘记使用以下代码运行迁移:</p> <pre><code class="language-py">python manage.py migrate python manage.py makemigrations python manage.py migrate </code></pre> <h2 id="2为视图和相应的模板编码">2.为视图和相应的模板编码</h2> <p>有了<a href="https://www.askpython.com/django/django-models" target="_blank">模型</a>之后,现在让我们对<a href="https://www.askpython.com/django/django-views" target="_blank">视图</a>进行编码。现在,对于完整的网站,我们需要以下视图:</p> <ol> <li><strong>首页视图:</strong>显示帖子列表</li> <li><strong>新帖子视图:</strong>显示所有最新的帖子</li> <li><strong>过去的帖子视图:</strong>显示 30 分钟或以上的帖子</li> <li><strong>单篇帖子视图:</strong>显示评论表单和已有评论</li> <li><strong>回复-评论视图:</strong>显示已有评论的回复表单</li> <li><strong>用户信息视图:</strong>显示用户信息</li> <li><strong>用户</strong>帖子<strong>视图:</strong>显示特定用户的帖子</li> <li><strong>提交视图:</strong>显示提交表单</li> <li><strong>编辑视图:</strong>编辑提交的表单</li> <li><strong>签到视图:</strong>显示签到页面</li> <li><strong>注册视图:</strong>显示注册页面</li> <li><strong>注销视图</strong>:注销用户</li> </ol> <p>除此之外,我们还需要<strong>两个</strong>视图来处理帖子的<strong>向上投票</strong>和<strong>向下投票</strong>。</p> <p>哇很多的观点!!所以让我们开始吧,不要浪费太多时间。</p> <h3 id="1主页视图">1.主页视图</h3> <p>所以在 <strong>Views.py</strong> 中,添加了 <strong>PostListView</strong> (主页)功能视图:</p> <pre><code class="language-py">def PostListView(request): posts = Post.objects.all() for post in posts: post.count_votes() post.count_comments() context = { 'posts': posts, } return render(request,'postlist.html',context) </code></pre> <p>对于每一篇帖子,我们在将它们显示在网页上之前都会计算总投票数和评论数。</p> <p><strong>urls.py</strong> 中的 url 端点:</p> <pre><code class="language-py">path('',PostListView, name='home'), </code></pre> <p>将<strong>postlist.html</strong>模板添加到 <strong>Django App</strong> 文件夹本身的<strong>模板</strong>文件夹中。</p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> <a href="{% url 'new_home'%}">New</a> <a href="{% url 'past_home'%}">Past</a> <a href="{% url 'submit'%}">Submit</a> {% if request.user.is_authenticated %} <div class="topnav-right"> <a href="{% url 'signout' %}">Sign Out </a> </div> {% else %} <div class="topnav-right"> <a href="{% url 'signin' %}">Sign In </a> </div> {% endif %} </div> <div class="w3-panel w3-light-grey w3-leftbar w3-border-grey"> <ol> {% for post in posts %} <li><p><a href = "{{post.url}}"><strong>{{post.title}}</strong></a> - <a href = "{% url 'vote' post.id %}">Upvote</a> - <a href = "{% url 'dvote' post.id %}">Downvote</a></p> {% if post.creator == request.user%} <p>{{post.votes}} votes | Created {{post.created_on}}| <a href = "{% url 'user_info' post.creator.username %}">{{post.creator.username}}</a> | <a href="{% url 'post' post.id %}"> {{post.comments}} Comments</a> | <a href="{% url 'edit' post.id %}"> Edit</a></p></li> {%else %} <p>{{post.votes}} votes | Created {{post.created_on}}| <a href = "{% url 'user_info' post.creator.username %}">{{post.creator.username}}</a> | <a href="{% url 'post' post.id %}"> {{post.comments}} Comments</a></p></li> {%endif%} {% endfor %} </ol> </div> {% endblock %} </code></pre> <p>这里,如果用户已经登录,我们将在导航栏中显示<strong>注销</strong>,如果用户没有登录,则显示登录。</p> <p>对于每个帖子,我们将显示<strong>帖子的标题、创建者、创建日期和时间、总投票数和评论。</strong></p> <p>此外,如果帖子的创建者是用户本身,那么我们也将显示一个<strong>编辑</strong>选项。</p> <h3 id="2新帖子和旧帖子视图">2.新帖子和旧帖子视图</h3> <p>新视图将首先显示所有最新的帖子。所以这样做的代码应该是:</p> <pre><code class="language-py">def NewPostListView(request): posts = Post.objects.all().order_by('-created_on') for post in posts: post.count_votes() post.count_comments() context = { 'posts': posts, } return render(request,'hnapp/postlist.html', context) </code></pre> <p>类似地,为了显示 30 分钟或更早之前创建的帖子,我们使用 Python 的 <strong><a href="https://www.askpython.com/python-modules/python-datetime-module" target="_blank">DateTime</a></strong> 库。因此,代码应该是:</p> <pre><code class="language-py">from datetime import datetime,timedelta from django.utils import timezone def PastPostListView(request): time = str((datetime.now(tz=timezone.utc) - timedelta(minutes=30))) posts = Post.objects.filter(created_on__lte = time) for post in posts: post.count_votes() post.count_comments() context={ 'posts': posts, } return render(request,'hnapp/postlist.html',context) </code></pre> <p>这里的 <strong>__lte</strong> 函数代表小于或等于的<strong>。因此,它会过滤掉 created_on 时间小于半小时前的所有帖子。</strong></p> <p>视图的 url 端点:</p> <pre><code class="language-py">path('new',NewPostListView, name='new_home'), path('past',PastPostListView, name='past_home'), </code></pre> <p>这两个模板将与<strong>主页</strong>视图相同。</p> <h3 id="3用户信息和用户帖子视图">3.用户信息和用户帖子视图</h3> <p>当客户点击<strong>帖子的创建者</strong>的名字时,他应该到达用户信息页面。</p> <p>用户信息页面应该显示<strong>用户名,创建日期,</strong>和一个<strong>链接</strong>到一个显示用户帖子的页面。</p> <p>因此,让我们在这里对用户信息和用户帖子视图进行编码:</p> <pre><code class="language-py">def UserInfoView(request,username): user = User.objects.get(username=username) context = {'user':user,} return render(request,'user_info.html',context) def UserSubmissions(request,username): user = User.objects.get(username=username) posts = Post.objects.filter(creator = user) for post in posts: post.count_votes() post.count_comments() return render(request,'user_posts.html',{'posts': posts}) </code></pre> <p>在 UserSubmissions 视图中,在显示帖子之前,我们使用循环的<a href="https://www.askpython.com/python/python-for-loop" target="_blank">计算总投票和评论。</a></p> <p>视图的 URL 端点是:</p> <pre><code class="language-py">path('user/<username>', UserInfoView, name='user_info'), path('posts/<username>',UserSubmissions, name='user_posts'), </code></pre> <p>相应的模板将是:</p> <p><strong>用户信息 html:</strong></p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> <a href="{% url 'new_home'%}">New</a> <a href="{% url 'past_home'%}">Past</a> <a href="{% url 'submit'%}">Submit</a> {% if request.user.is_authenticated %} <div class="topnav-right"> <a href="{% url 'signout' %}">Sign Out </a> </div> {% else %} <div class="topnav-right"> <a href="{% url 'signin' %}">Sign In </a> </div> {% endif %} </div> <div class="w3-panel w3-light-grey w3-leftbar w3-border-grey"> <p><strong>User: </strong>{{user.username}}</p> <p><strong>Created: </strong>{{user.date_joined}}</p> </div> <a href="{% url 'user_posts' user.username %}">Submissions</a> {% endblock %} </code></pre> <p><strong>user_post.html:</strong></p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> <a href="{% url 'new_home'%}">New</a> <a href="{% url 'past_home'%}">Past</a> <a href="{% url 'submit'%}">Submit</a> {% if request.user.is_authenticated %} <div class="topnav-right"> <a href="{% url 'signout' %}">Sign Out </a> </div> {% else %} <div class="topnav-right"> <a href="{% url 'signin' %}">Sign In </a> </div> {% endif %} </div> <ol> {%for post in posts%} <div class="w3-panel w3-light-grey w3-leftbar w3-border-grey"> <li><p><a href = "{{post.url}}">{{post.title}}</a></p> <p>{{post.votes}} | Created {{post.created_on}}| <a href = "{% url 'user_info' post.creator.username %}">{{post.creator.username}}</a> | <a href="{% url 'post' post.id %}"> {{post.comments}} Comments</a></p></li> </div> {% endfor %} </ol> {% endblock %} </code></pre> <h3 id="4提交和编辑视图">4.提交和编辑视图</h3> <p>好了,现在,让我们编写<strong>提交视图</strong>和<strong>编辑视图</strong>的代码。如果用户已经登录,提交页面应该显示一个提交表单。</p> <p>编辑页面也会做同样的工作,但是它会更新一个现有的帖子,而不是创建一个新的。</p> <p>所以两个函数视图将是:</p> <pre><code class="language-py">from datetime import datetime def SubmitPostView(request): if request.user.is_authenticated: form = PostForm() if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] url = form.cleaned_data['url'] description = form.cleaned_data['description'] creator = request.user created_on = datetime.now() post = Post(title=title, url=url, description=description, creator = creator, created_on=created_on) post.save() return redirect('/') return render(request,'submit.html',{'form':form}) return redirect('/signin') def EditPostView(request,id): post = get_object_or_404(Post,id=id) if request.method =='POST': form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect('/') form = PostForm(instance =post) return render(request,'submit.html',{'form':form}) </code></pre> <p>在 SubmitPostView 中,我们创建了一个全新的 Post 对象,而在 EditPostView 中,我们只是更新了现有的对象。</p> <p>这两个视图的 URL 端点是:</p> <pre><code class="language-py">path('submit',SubmitPostView, name='submit'), path('edit/<int:id>',EditListView, name='edit') </code></pre> <p>还要在 <strong>forms.py</strong> 文件中添加 PostForm:</p> <pre><code class="language-py">from django import forms from .models import Comment,Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','url','description') </code></pre> <p>此外,它们的模板是相同的,因为两者都显示相同的表单</p> <p>因此, <strong>submit.html:</strong></p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> {% if request.user.is_authenticated %} <div class="topnav-right"> <a href="{% url 'signout' %}">Sign Out </a> </div> {% else %} <div class="topnav-right"> <a href="{% url 'signin' %}">Sign In</a> </div> {% endif %} </div> <div class="w3-panel w3-light-grey w3-leftbar w3-border-grey"> <form method ='post'> {% csrf_token %} {{form.as_p}} <input type="submit" value = "Submit"> </form> </div> {% endblock %} </code></pre> <h3 id="5注册登录和注销视图">5.注册、登录和注销视图</h3> <p>这里我们将使用<strong><a href="https://www.askpython.com/django/django-user-authentication" target="_blank">django . contrib . auth</a></strong>库来认证、登录和注销用户。</p> <p>此外,我们将使用内置的 Django 用户模型,AuthenticationForm,和<strong>用户创建表单。</strong></p> <p>所以观点会是:</p> <pre><code class="language-py">from django.contrib.auth import authenticate,login,logout from django.contrib.auth.forms import AuthenticationForm,UserCreationForm def signup(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username = username,password = password) login(request, user) return redirect('/') else: return render(request,'auth_signup.html',{'form':form}) else: form = UserCreationForm() return render(request,'auth_signup.html',{'form':form}) def signin(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username =username, password = password) if user is not None: login(request,user) return redirect('/') else: form = AuthenticationForm() return render(request,'auth_signin.html',{'form':form}) else: form = AuthenticationForm() return render(request, 'auth_signin.html', {'form':form}) def signout(request): logout(request) return redirect('/') </code></pre> <p><strong>视图的 URL 端点:</strong></p> <pre><code class="language-py">path('signin',signin, name='signin'), path('signup',signup, name='signup'), path('signout',signout, name='signout'), </code></pre> <p><strong>auth_signup.html</strong> 和 <strong>auth_signin.html</strong> 都将显示表单以获取用户凭证。</p> <p>因此, <strong>auth_signup.html</strong> 将是:</p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> <a href="{% url 'new_home'%}">New</a> <a href="{% url 'past_home'%}">Past</a> <a href="{% url 'submit'%}">Submit</a> </div> <form method ='post'> {% csrf_token %} {{form.as_p}} <input type="submit" value = "Submit"> </form> <br> <h3>Already Have an Account??</h3> <a href = "{% url 'signin' %}">Sign In Here</a> {% endblock %} </code></pre> <p>以及 <strong>auth_signin.html</strong></p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> <a href="{% url 'new_home'%}">New</a> <a href="{% url 'past_home'%}">Past</a> <a href="{% url 'submit'%}">Submit</a> </div> <form method ='post'> {% csrf_token %} {{form.as_p}} <input type="submit" value = "Submit"> </form> <br> <h3>Dont have an account??</h3> <a href = "{% url 'signup' %}">SignUp Here</a> {% endblock %} </code></pre> <h3 id="6向上投票和向下投票逻辑编码">6.向上投票和向下投票逻辑编码</h3> <p>每当用户点击 <strong>Upvote</strong> 按钮,该帖子的投票数就会增加<strong>一个</strong>,反之亦然 <strong>Downvote</strong> 。</p> <p>另外,<strong>注意</strong>一个用户<strong>不能在一个特定的帖子上投赞成票/反对票超过一次</strong>。所以现在让我们为向上投票和向下投票的视图编码</p> <pre><code class="language-py">def UpVoteView(request,id): if request.user.is_authenticated: post = Post.objects.get(id=id) votes = Vote.objects.filter(post = post) v = votes.filter(voter = request.user) if len(v) == 0: upvote = Vote(voter=request.user,post=post) upvote.save() return redirect('/') return redirect('/signin') def DownVoteView(request,id): if request.user.is_authenticated: post = Post.objects.get(id=id) votes = Vote.objects.filter(post = post) v = votes.filter(voter = request.user) if len(v) != 0: v.delete() return redirect('/') return redirect('/signin') </code></pre> <p>这里的逻辑很简单:</p> <ul> <li><strong>UpVoteView:</strong> 如果对于一个<strong>特定帖子</strong>,一个特定用户的投票数<strong>等于零</strong>,那么在投票模型中创建并保存该用户的一个新的 upvote。</li> <li><strong>DownVoteView:</strong> 如果对于<strong>某个帖子</strong>,某个特定用户的投票数<strong>不等于,即大于零</strong>,则从投票模型中删除该用户的 upvote</li> </ul> <p>两者的 URL 端点:</p> <pre><code class="language-py">path('vote/<int:id>',UpVoteView,name='vote'), path('downvote/<int:id>',DownVoteView,name='dvote'), </code></pre> <p>不错!!</p> <h3 id="7对评论页面视图编码">7.对评论页面视图编码</h3> <p>现在是项目最激动人心的部分。评论视图应该显示<strong>评论表单</strong>。此外,它应该显示评论和相应的回复在<strong>正确的线程顺序</strong>。</p> <p>也就是说,评论应该只按下面的顺序显示: <strong>C1</strong> 然后<strong>C1-孩子</strong>然后<strong>C1-孩子的孩子</strong>,然后 <strong>C2,C2-孩子,</strong>等等。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6a9007b41a82e421470909e39275183f.png" alt="Thread Sequence" loading="lazy"></p> <p>Thread Sequence</p> <p>为此,我们将使用一个递归函数,将<strong>标识符</strong>和<strong>父实例作为参数</strong>。因此对于特定的帖子= <strong>帖子</strong>。</p> <p>递归函数如下所示:</p> <pre><code class="language-py">def func(i,parent): children = Comment.objects.filter(post =post).filter(identifier =i).filter(parent=parent) for child in children: gchildren = Comment.objects.filter(post =post).filter(identifier = i+1).filter(parent=child) if len(gchildren)==0: comments.append(child) else: func(i+1,child) comments.append(child) </code></pre> <p>我们首先获取所有孩子对某个特定家长评论的评论。然后我们发现每个子实例有多少个子实例。</p> <p>如果<strong>孩子</strong>没有任何孙辈(gchild),即。这是该父评论的最底部回复。因此,我们将<strong>子节点</strong>保存到一个空列表中。</p> <p>如果<strong>孩子</strong>有“<strong>孩子,”</strong>,那么我们再次使用函数,将<strong>孩子</strong>作为父参数。我们这样做,直到我们到达线程的底部。到达那里后,我们将注释实例添加到列表中。</p> <p>因此,每个线程将以相反的顺序添加到列表中,首先保存最底部的线程注释,最后保存最顶部的。</p> <p>但是,我们需要以正确的顺序显示评论线程,评论(标识符=0)在上面,后续的回复在下面。所以在显示它们之前,我们使用 Python 列表的 <strong>reversed(list)</strong> 属性。</p> <p>因此,完整的<strong>注释视图</strong>将是:</p> <pre><code class="language-py">def CommentListView(request,id): form = CommentForm() post = Post.objects.get(id =id) post.count_votes() post.count_comments() comments = [] def func(i,parent): children = Comment.objects.filter(post =post).filter(identifier =i).filter(parent=parent) for child in children: gchildren = Comment.objects.filter(post =post).filter(identifier = i+1).filter(parent=child) if len(gchildren)==0: comments.append(child) else: func(i+1,child) comments.append(child) func(0,None) if request.method == "POST": if request.user.is_authenticated: form = CommentForm(request.POST) if form.is_valid(): content = form.cleaned_data['content'] comment = Comment(creator = request.user,post = post,content = content,identifier =0) comment.save() return redirect(f'/post/{id}') return redirect('/signin') context ={ 'form': form, 'post': post, 'comments': list(reversed(comments)), } return render(request,'commentpost.html', context) </code></pre> <p>我们调用 <strong>func(0,None)</strong> 因为我们想要完整的注释线程。</p> <p>视图的 URL 端点:</p> <pre><code class="language-py">path('post/<int:id>',CommentListView, name='post') </code></pre> <p>我们还需要一个评论表来提交评论。因此在 <strong>forms.py</strong> 中,添加 CommentForm:</p> <pre><code class="language-py">class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) </code></pre> <p>并且<strong>commentpost.html</strong>应该显示表单和线程注释。</p> <p>So <strong>commentpost.html:</strong></p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> <a href="{% url 'new_home'%}">New</a> <a href="{% url 'past_home'%}">Past</a> <a href="{% url 'submit'%}">Submit</a> {% if request.user.is_authenticated %} <div class="topnav-right"> <a href="{% url 'signout' %}">Sign Out </a> </div> {% else %} <div class="topnav-right"> <a href="{% url 'signin' %}">Sign In </a> </div> {% endif %} </div> <div class="w3-panel w3-light-grey w3-leftbar w3-border-grey"> <p><a href = "{{post.url}}"><strong>Title: {{post.title}}</strong></a></p> {% if post.creator == request.user%} <p>{{post.votes}} votes | Created {{post.created_on}}| <a href = "{% url 'user_info' post.creator.username %}">{{post.creator.username}}</a> | {{post.comments}} Comments | <a href="{% url 'edit' post.id %}"> Edit</a></p> {%else %} <p>{{post.votes}} votes | Created {{post.created_on}}| <a href = "{% url 'user_info' post.creator.username %}">{{post.creator.username}}</a> | {{post.comments}} Comments</p> {% endif %} <p><strong>Description: </strong>{{post.description}}</p> <form method ='post'> {% csrf_token %} {{form.as_p}} <input type="submit" value = "Submit"> </form> <br> </div> {% for comment in comments %} {% if comment.identifier %} <div class="w3-panel w3-orange w3-leftbar w3-border-red"> <p class="ex1" style="font-family:helvetica;" style="color:black"><a href = "{% url 'user_info' comment.creator.username %}">Comment by: {{comment.creator.username}}</a> | Thread Level: {{comment.identifier}}</p> <p class="ex1" style="font-family:helvetica;" style="color:black"><strong>{{comment.content}}</strong></p> <p class="ex1" style="font-family:helvetica;" style="color:black"><a href = "{% url 'reply' id1=post.id id2=comment.id %}">reply</a></p> </div> {% else %} <div class="w3-panel w3-red w3-leftbar w3-border-orange"> <p style="font-family:helvetica;" style="color:black"><a href = "{% url 'user_info' comment.creator.username %}">Comment by: {{comment.creator.username}}</a> | Thread Level: {{comment.identifier}}</p> <p style="font-family:helvetica;" style="color:black"><strong>{{comment.content}}</strong></p> <p style="font-family:helvetica;" style="color:black"><a href = "{% url 'reply' id1=post.id id2=comment.id %}">reply</a></p> </div> {% endif %} {% endfor %} </code></pre> <h3 id="8编写回复评论视图的代码">8.编写回复评论视图的代码</h3> <p>现在,当我们点击评论下面的回复按钮时,我们应该得到一个<strong>表单</strong>来提交我们的回复。</p> <p>因此<strong>注释视图</strong>将为:</p> <pre><code class="language-py">def CommentReplyView(request,id1,id2): form = CommentForm() comment = Comment.objects.get(id = id2) post = Post.objects.get(id=id1) if request.method == "POST": if request.user.is_authenticated: form = CommentForm(request.POST) if form.is_valid(): reply_comment_content = form.cleaned_data['content'] identifier = int(comment.identifier + 1) reply_comment = Comment(creator = request.user, post = post, content = reply_comment_content, parent=comment, identifier= identifier) reply_comment.save() return redirect(f'/post/{id1}') return redirect('/signin') context ={ 'form': form, 'post': post, 'comment': comment, } return render(request,'reply_post.html', context) </code></pre> <p>回复评论将有一个<strong>父实例</strong>,不像普通的帖子评论有<strong>父实例=无</strong>。</p> <p>视图的 URL 端点:</p> <pre><code class="language-py">path('post/<int:id1>/comment/<int:id2>',CommentReplyView,name='reply'), </code></pre> <p><strong>reply_post.html</strong> 应该显示父评论实例和回复表单。</p> <p>因此,模板 <strong>reply_post.html</strong> 将是:</p> <pre><code class="language-py">{% extends 'base.html' %} {% block content %} <div class="topnav"> <a class="active" href="{% url 'home'%}">Hacker News</a> <a href="{% url 'new_home'%}">New</a> <a href="{% url 'past_home'%}">Past</a> <a href="{% url 'submit'%}">Submit</a> {% if request.user.is_authenticated %} <div class="topnav-right"> <a href="{% url 'signout' %}">Sign Out </a> </div> {% else %} <div class="topnav-right"> <a href="{% url 'signin' %}">Sign In </a> </div> {% endif %} </div> <div class="w3-panel w3-light-grey w3-leftbar w3-border-grey"> <p> <h5><a href = "{% url 'user_info' comment.creator.username %}">{{comment.creator.username}}</a> | On : <a href = "{% url 'post' post.id %}">{{post.title}}</a></h5></p> <p>{{comment.content}}</p> <form method ='post'> {% csrf_token %} {{form.as_p}} <input type="submit" value = "Submit"> </form> </div> {% endblock %} </code></pre> <p>太好了!!就这样伙计们!!</p> <h2 id="django-项目的最终代码">Django 项目的最终代码</h2> <p><strong>整个项目可以在我的 <a href="https://github.com/nishant-gudipaty/Hacker-News-Clone" target="_blank">Github 简介</a>中找到</strong>。请随意在您的系统中克隆存储库,并使用代码。为了您的方便,我也贴出了下面每个文件的完整代码。</p> <h3 id="1modelspy">1.Models.py</h3> <pre><code class="language-py">from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField("HeadLine", max_length=256, unique=True) creator = models.ForeignKey(User, on_delete= models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) url = models.URLField("URL", max_length=256,blank=True) description = models.TextField("Description", blank=True) votes = models.IntegerField(null=True) comments = models.IntegerField(null=True) def __unicode__(self): return self.title def count_votes(self): self.votes = Vote.objects.filter(post = self).count() def count_comments(self): self.comments = Comment.objects.filter(post = self).count() class Vote(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __unicode__(self): return f"{self.user.username} upvoted {self.link.title}" class Comment(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() identifier = models.IntegerField() parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True) def __unicode__(self): return f"Comment by {self.user.username}" </code></pre> <h3 id="2viewspy">2.Views.py</h3> <pre><code class="language-py">from django.shortcuts import render,redirect,get_object_or_404 from django.views.generic import ListView from .models import Post,Vote,Comment from .forms import CommentForm,PostForm from django.contrib.auth.models import User from django.contrib.auth import authenticate,login,logout from django.contrib.auth.forms import AuthenticationForm,UserCreationForm from datetime import datetime,timedelta from django.utils import timezone from django.contrib.auth import authenticate,login,logout from django.contrib.auth.forms import AuthenticationForm,UserCreationForm # Create your views here. def PostListView(request): posts = Post.objects.all() for post in posts: post.count_votes() post.count_comments() context = { 'posts': posts, } return render(request,'hnapp/postlist.html',context) def NewPostListView(request): posts = Post.objects.all().order_by('-created_on') for post in posts: post.count_votes() post.count_comments() context = { 'posts': posts, } return render(request,'hnapp/postlist.html', context) def PastPostListView(request): time = str((datetime.now(tz=timezone.utc) - timedelta(minutes=30))) posts = Post.objects.filter(created_on__lte = time) for post in posts: post.count_votes() post.count_comments() context={ 'posts': posts, } return render(request,'hnapp/postlist.html',context) def UpVoteView(request,id): if request.user.is_authenticated: post = Post.objects.get(id=id) votes = Vote.objects.filter(post = post) v = votes.filter(voter = request.user) if len(v) == 0: upvote = Vote(voter=request.user,post=post) upvote.save() return redirect('/') return redirect('/signin') def DownVoteView(request,id): if request.user.is_authenticated: post = Post.objects.get(id=id) votes = Vote.objects.filter(post = post) v = votes.filter(voter = request.user) if len(v) != 0: v.delete() return redirect('/') return redirect('/signin') def UserInfoView(request,username): user = User.objects.get(username=username) context = {'user':user,} return render(request,'hnapp/userinfo.html',context) def UserSubmissions(request,username): user = User.objects.get(username=username) posts = Post.objects.filter(creator = user) print(len(posts)) for post in posts: post.count_votes() post.count_comments() return render(request,'hnapp/user_posts.html',{'posts': posts}) def EditListView(request,id): post = get_object_or_404(Post,id=id) if request.method =='POST': form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect('/') form = PostForm(instance =post) return render(request,'hnapp/submit.html',{'form':form}) def CommentListView(request,id): form = CommentForm() post = Post.objects.get(id =id) post.count_votes() post.count_comments() comments = [] def func(i,parent): children = Comment.objects.filter(post =post).filter(identifier =i).filter(parent=parent) for child in children: gchildren = Comment.objects.filter(post =post).filter(identifier = i+1).filter(parent=child) if len(gchildren)==0: comments.append(child) else: func(i+1,child) comments.append(child) func(0,None) if request.method == "POST": if request.user.is_authenticated: form = CommentForm(request.POST) if form.is_valid(): content = form.cleaned_data['content'] comment = Comment(creator = request.user,post = post,content = content,identifier =0) comment.save() return redirect(f'/post/{id}') return redirect('/signin') context ={ 'form': form, 'post': post, 'comments': list(reversed(comments)), } return render(request,'hnapp/post.html', context) def CommentReplyView(request,id1,id2): form = CommentForm() comment = Comment.objects.get(id = id2) post = Post.objects.get(id=id1) if request.method == "POST": if request.user.is_authenticated: form = CommentForm(request.POST) if form.is_valid(): reply_comment_content = form.cleaned_data['content'] identifier = int(comment.identifier + 1) reply_comment = Comment(creator = request.user, post = post, content = reply_comment_content, parent=comment, identifier= identifier) reply_comment.save() return redirect(f'/post/{id1}') return redirect('/signin') context ={ 'form': form, 'post': post, 'comment': comment, } return render(request,'hnapp/reply_post.html', context) def SubmitPostView(request): if request.user.is_authenticated: form = PostForm() if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] url = form.cleaned_data['url'] description = form.cleaned_data['description'] creator = request.user created_on = datetime.now() post = Post(title=title, url=url, description=description, creator = creator, created_on=created_on) post.save() return redirect('/') return render(request,'hnapp/submit.html',{'form':form}) return redirect('/signin') def signup(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username = username,password = password) login(request, user) return redirect('/') else: return render(request,'hnapp/auth_signup.html',{'form':form}) else: form = UserCreationForm() return render(request,'hnapp/auth_signup.html',{'form':form}) def signin(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username =username, password = password) if user is not None: login(request,user) return redirect('/') else: form = AuthenticationForm() return render(request,'hnapp/auth_signin.html',{'form':form}) else: form = AuthenticationForm() return render(request, 'hnapp/auth_signin.html', {'form':form}) def signout(request): logout(request) return redirect('/') </code></pre> <h3 id="3-urlspy">3. Urls.py</h3> <pre><code class="language-py">from django.contrib import admin from django.urls import path from .views import * urlpatterns = [ path('',PostListView, name='home'), path('new',NewPostListView, name='new_home'), path('past',PastPostListView, name='past_home'), path('user/<username>', UserInfoView, name='user_info'), path('posts/<username>',UserSubmissions, name='user_posts'), path('post/<int:id>',CommentListView, name='post'), path('submit',SubmitPostView, name='submit'), path('signin',signin, name='signin'), path('signup',signup, name='signup'), path('signout',signout, name='signout'), path('vote/<int:id>',UpVoteView,name='vote'), path('downvote/<int:id>',DownVoteView,name='dvote'), path('edit/<int:id>',EditListView, name='edit'), path('post/<int:id1>/comment/<int:id2>',CommentReplyView,name='reply'), ] </code></pre> <h3 id="4formspy">4.Forms.py</h3> <pre><code class="language-py">from django import forms from .models import Comment,Post class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','url','description') </code></pre> <h3 id="6-adminpy">6. Admin.py</h3> <pre><code class="language-py">from django.contrib import admin from .models import * # Register your models here. admin.site.register(Post) admin.site.register(Vote) admin.site.register(Comment) #admin.site.register(UserInfo) </code></pre> <h2 id="守则的实施">守则的实施</h2> <p>编码部分就这样了!!现在运行服务器</p> <pre><code class="language-py">python manage.py runserver </code></pre> <p>并进入主页:"<strong>www.localhost.com</strong>"</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ce8f48eaf080b9c4bea326239bd6765e.png" alt="Home Page" loading="lazy"></p> <p>Home Page</p> <p>没有帖子,请点击登录:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/d5d6d279dbe001598c48850acdd23481.png" alt="Signin " loading="lazy"></p> <p>Signin</p> <p>点击在此注册并注册您的帐户</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8239e502c60919470165a97467349c72.png" alt="Signup" loading="lazy"></p> <p>Signup</p> <p>注册完成后,请提交并添加一些帖子</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/465b0b1ed049b030914252c6bad2af4d.png" alt="Submit " loading="lazy"></p> <p>Submit</p> <p>我在那里提交了几篇文章,所以现在点击导航栏上的黑客新闻按钮进入主页:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/efb041828fee7530a8936f0526917bb9.png" alt="Home Page Posts" loading="lazy"></p> <p>Home Page Posts</p> <p>你现在可以<strong>投票赞成</strong>和<strong>投票反对</strong>帖子。同样点击<strong>新</strong>和<strong>过去</strong>按钮。现在点击帖子下方的用户名——<strong>我的情况是 Nishant</strong> :</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8f42e492987c0c45fde565f4a8a2d1fc.png" alt="User" loading="lazy"></p> <p>User</p> <p>你会看到<strong>用户信息</strong>以及<strong>提交</strong>按钮。好了,现在回去点击<strong>评论;</strong>您将进入评论页面</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/58fc79ed8b830eba4835abef16d5b55e.png" alt="Post " loading="lazy"></p> <p>Post</p> <p>提交评论</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fcedc55a5bec9fbecbcb74854dc68fd8.png" alt="Comment" loading="lazy"></p> <p>Comment</p> <p>这就是我们最热门的评论。现在当点击回复时:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/159f0f84f8e1b7b367e5bc88bd47d1d3.png" alt="Reply To Comment 1 " loading="lazy"></p> <p>Reply To Comment 1</p> <p>输入随机回复,然后单击提交。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/86e4a7aa86c3b0ba0294d67f7a509d58.png" alt="Reply Thread" loading="lazy"></p> <p>Reply Thread</p> <p>参见线程级别= 1,已经重新安排了自己,使得父注释在顶部。这就是递归函数正在做的事情。尝试添加更多的回复,看看它如何安排自己。</p> <p>太好了!!我们自己的姜戈项目的想法变成了现实。</p> <h2 id="参考-5">参考</h2> <ul> <li><a href="https://www.askpython.com/django/django-models" target="_blank">Django 车型</a></li> <li><a href="https://www.askpython.com/django/django-views" target="_blank">Django 观点</a></li> <li><a href="https://www.askpython.com/django/django-templates" target="_blank">Django 模板</a></li> <li><a href="https://www.askpython.com/django/django-model-forms" target="_blank">Django 模型表格</a></li> </ul> <h2 id="结论-29">结论</h2> <p>就这样,伙计们!你自己的黑客新闻网络应用已经准备好了。为了更好地理解,请尝试自己实现所有的逻辑代码!</p> <h1 id="python-中处理精度值的-5-种方法">Python 中处理精度值的 5 种方法</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/handle-precision-values" target="_blank">https://www.askpython.com/python/examples/handle-precision-values</a></p> </blockquote> <p>读者朋友们,你们好!在本文中,我们将关注 Python 中处理精度值的 <strong>5 种方法。所以,让我们开始吧!</strong></p> <hr> <h2 id="处理精度值是什么意思">“处理精度值”是什么意思?</h2> <p>无论是哪种编程语言,我们经常会遇到这样的情况:在任何应用程序或操作步骤中处理整数或数字数据。在同样的过程中,我们找到了十进制值的数据。这就是我们需要处理精度值的时候。</p> <p>Python 为我们提供了各种函数来处理整数数据的精度值。它让我们可以根据十进制值在数字中的位置,选择是排除小数点,还是自定义值。</p> <h2 id="python-中如何处理精度值">Python 中如何处理精度值?</h2> <p>让我们看看 Python 为处理代码输出中的精度数据和小数提供的不同函数。</p> <ol> <li><strong>Python %运算符</strong></li> <li><strong>Python 格式()函数</strong></li> <li><strong>Python round()函数</strong></li> <li><strong>trunc()函数</strong></li> <li><strong>数学 ceil() & floor()函数</strong></li> </ol> <p>现在,让我们在接下来的部分中逐一了解一下。</p> <hr> <h3 id="1python-运算符">1。Python %运算符</h3> <p>使用 <a href="https://www.askpython.com/python/python-modulo-operator-math-fmod" target="_blank">'% '操作符</a>,我们可以格式化数字以及设置相同的精度限制。这样,我们可以定制要包含在结果数中的精度点的限制。</p> <p>看看下面的语法!</p> <p><strong>语法:</strong></p> <pre><code class="language-py">'%.point'%number </code></pre> <ul> <li>点:它是指我们希望在数字的小数点后有多少个点。</li> <li>number:要处理的整数值。</li> </ul> <hr> <h3 id="2python-format函数">2。Python format()函数</h3> <p>像%操作符一样,我们也可以使用 <a href="https://www.askpython.com/python/string/python-format-function" target="_blank">format()函数</a>,它帮助我们设置精度值的限制。使用 format()函数,我们将数据格式化为一个字符串,并设置数字小数部分后包含的点数的限制。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">print ("{0:.pointf}".format(number)) </code></pre> <hr> <h3 id="3python-round函数">3。Python round()函数</h3> <p>使用 Python round()函数,我们可以提取并以自定义格式显示整数值,也就是说,我们可以选择小数点后要显示的位数,作为精度处理的检查。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">round(number, point) </code></pre> <hr> <h2 id="在-python-中实现精度处理">在 Python 中实现精度处理</h2> <p>在下面的例子中,我们利用了上面解释的 3 个函数来处理 Python 中的精度值。我们在这里试图通过将小数点后显示的数字设置为 4 来处理精度。</p> <pre><code class="language-py">num = 12.23456801 # using "%" operator print ('%.4f'%num) # using format() function print ("{0:.4f}".format(num)) # using round() function print (round(num,4)) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">12.2346 12.2346 12.2346 </code></pre> <hr> <h2 id="python-数学函数处理精度">Python 数学函数处理精度</h2> <p>除了上述函数,python 还为我们提供了<a href="https://www.askpython.com/python-modules/python-math-module" target="_blank">数学模块</a>,它包含了一组处理精度值的函数。</p> <p>Python 数学模块具有以下一组处理精度值的函数——</p> <ol> <li>trunc()函数</li> <li>Python ceil()和 floor()函数</li> </ol> <p>让我们一个一个来看看。</p> <hr> <h3 id="4python-trunc函数">4。Python trunc()函数</h3> <p>使用 trunc()函数,小数点后的所有数字都被终止。也就是说,它只返回小数点前面的数字。</p> <p>看看下面的语法。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">import math math.trunc(number) </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">import math num = 12.23456801 # using trunc() function print (math.trunc(num)) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">12 </code></pre> <hr> <h3 id="5python-ceil和-floor函数">5.Python ceil()和 floor()函数</h3> <p>使用 ceil()和 floor()函数,我们可以将十进制数四舍五入到最接近的高值或低值。</p> <p>ceil()函数将十进制数四舍五入到其后最接近的大值。另一方面,floor()函数将该值舍入到它前面最近的低值。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">import math num = 12.23456801 # using ceil() function print (math.ceil(num)) # using floor() function print (math.floor(num)) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">13 12 </code></pre> <hr> <h2 id="结论-30">结论</h2> <p>如果你遇到任何问题,欢迎在下面评论。更多与 Python 编程相关的帖子,请继续关注我们。</p> <p>在那之前,学习愉快!!🙂</p> <h1 id="在-python-中处理-ioerrors-完全指南">在 Python 中处理 IOErrors 完全指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/handling-ioerrors" target="_blank">https://www.askpython.com/python/examples/handling-ioerrors</a></p> </blockquote> <p>在本文中,我们将学习在 Python 中处理 IOErrors,假设我们正在对一个特定的例子执行数学运算。当它很长的时候,可能会更悲惨。当我们被困在某个地方时,主要问题就出现了。经过很多努力,我们解决了这个问题。但是,答案并不令人满意或者是错误的。这有两种可能性:</p> <ol> <li>要么我们试图解决的问题从一开始就被错误地构建。</li> <li>或者我们在整个过程或步骤中输入错误。</li> </ol> <p>整个事情用一个简单的词来说就是一个<strong>错误</strong>。在不同的条件下,它们可以是不同的类型。这要看问题本身。同样的,编程中也有<strong>错误。</strong>它们是<strong>输出</strong>的不同形式,出现在特殊情况下。</p> <h2 id="python-中的-ioerror-是什么">Python 中的 IOError 是什么?</h2> <p><em>IOError 表示输入/输出错误。当我们引用的文件、文件路径或操作系统操作不存在时,就会出现这种情况。例如,如果您在一个现有文件上运行运行时操作,并且该文件从该位置丢失,Python 将抛出一个 IOError。</em></p> <p>现在,在我们学习如何在 Python 中处理 IOErrors 之前,让我们了解不同类型的错误。</p> <h3 id="python-中的错误类型">Python 中的错误类型</h3> <p>编译器将错误分成不同的类别,以便更好地识别和解决问题。下面是您在编程过程中会遇到的一些最常见的错误类型。</p> <ol> <li>当我们试图将一个数除以零时就会出现错误。</li> <li><strong>AssertionError</strong> :当一个 Python 脚本的调试或者<a href="https://www.askpython.com/python/built-in-methods/assertions-in-python" target="_blank">断言语句</a>失败时,就会出现这个。</li> <li><strong>AttributeError</strong> :当给定的属性错误或者在模块或脚本中不存在时。</li> <li><strong>FloatingPointError</strong> :浮点实现过程中的错误。</li> <li><strong>ImportError</strong>/<strong>ModuleNotFoundError</strong>:如果我们试图<a href="https://www.askpython.com/python/python-import-statement" target="_blank">导入一个模块</a>而它并不存在,那么这将引发。</li> <li><em><strong>IOError</strong> :当我们试图访问的文件在系统中不存在时引发。</em></li> </ol> <p>您可以通过这个<a href="https://docs.python.org/3/library/exceptions.html" target="_blank">链接</a>从官方 Python 文档中浏览更多关于不同异常的信息。</p> <h2 id="在-python-中检测和处理-ioerrors">在 Python 中检测和处理 IOErrors</h2> <p>通常,在较新的 Python 版本中,这个异常有一个新的名称。</p> <h3 id="在文件操作期间处理-python-中的-ioerrors">在文件操作期间处理 Python 中的 IOErrors</h3> <p>让我们创建一个函数来引用一个文件,然后我们将处理 IOError。</p> <p><strong>代码:</strong></p> <pre><code class="language-py">file = open('sample.txt', 'w') print('The file name is: ', file.name) print('Openeing mode: ', file.mode) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/518fc42b9da2c13b695af0924dc4e2da.png" alt="Opening A File Detecting and Handling IOErrors in Python" loading="lazy"></p> <p>Opening A File</p> <pre><code class="language-py">file.close() print('File is closed: ', file.closed) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/114863d64ec4eff6cb2377a981616e03.png" alt="Closing A File 2 Detecting and Handling IOErrors in Python" loading="lazy"></p> <p>Closing a file</p> <p>现在,我们将删除该文件,然后尝试打开它,这将引发所需的错误。</p> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ace4dbb6fd41875f4896ea9951a96516.png" alt="FileNotFoundError 1 Detecting and Handling IOErrors in Python" loading="lazy"></p> <p>FileNotFoundError occurred</p> <p>FileNotFoundError 是 IOError 的子类。我们也可以使用 Python 中的异常处理方法来检测它。</p> <p>让我们使用 <a href="https://www.askpython.com/python/python-exception-handling" target="_blank">try and catch 块</a>来处理我们的 filenotfounderror,并为我们提供更好、更容易理解的输出。</p> <pre><code class="language-py">try: file = open('sample.txt', 'w') print('File found!!!') except IOError: print('File not found!!!') # Output: File not found!!! </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ec4a1fb57352f55941987b7eaaa70182.png" alt="Error Detection" loading="lazy"></p> <p>Error Detection</p> <p><strong>说明:</strong></p> <ol> <li>在 try 块中,我们尝试以读取模式打开文件。</li> <li>然后我们添加一条消息,如果文件存在,则打印<strong>“文件找到”</strong>。</li> <li>如果文件不存在,except 语句会处理这个问题。</li> <li>当一个错误发生时,这个块将捕获错误并打印出<strong>文件未找到</strong>,而不是我们之前看到的复杂错误消息。</li> </ol> <h2 id="结论-31">结论</h2> <p>因此,处理 IOError 的主题结束了。该错误特别符合 Python 编程的文件处理标准。这是一个容易研究的话题,我们可以使用<strong>try-except</strong>块来消除错误。再次修改简单的代码以获得更清晰的概念。</p> <p>我希望你喜欢这篇非常简短的关于在 Python 中使用 IOErrors 的指南。</p> <h1 id="在-python-中处理用于机器学习的大数据集">在 Python 中处理用于机器学习的大数据集</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/handling-large-datasets-machine-learning" target="_blank">https://www.askpython.com/python/examples/handling-large-datasets-machine-learning</a></p> </blockquote> <p>大型数据集现在已经成为我们机器学习和数据科学项目的一部分。如此大的数据集不适合 RAM,并且不可能对其应用机器学习算法。你的系统变得很慢,这也让你无法执行其他任务。因此,在本教程中,我们将学习如何为您的机器学习或数据科学项目处理大型数据集。</p> <h2 id="用熊猫处理大型数据集">用熊猫处理大型数据集</h2> <p><a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">Pandas</a> 模块最广泛用于数据操作和分析。它提供了强大的数据框架,支持 CSV、JSON 等文件格式,并且易于删除重复项和数据清理。</p> <p>然而,处理大型数据集仍然是熊猫面临的一个问题。以下是你可以尝试的方法。</p> <p>我们将使用各种方法从 Kaggle 加载 <a href="https://www.kaggle.com/edwinytleung/nyc-yellow-taxi-2015-sample-data" target="_blank">NYC Yellow Taxi 2015 数据集</a>的训练数据集,并使用<code>psutil.virtual_memory()</code>查看内存消耗。</p> <h3 id="1将您的数据分块">1.将您的数据分块</h3> <p>如果您不需要同时使用所有数据,您可以分块加载数据。组块是我们数据集的一部分。我们可以使用<code>read_csv()</code>并传递一个参数<code>chunksize</code>。块大小取决于你有多少内存。</p> <pre><code class="language-py">import pandas as pd import psutil # Loading the training dataset by chunking dataframe memory_timestep_1 = psutil.virtual_memory() data_iterator = pd.read_csv("dataset/train_2015.csv", chunksize=100000) fare_amount_sum_chunk = 0 for data_chunk in data_iterator: fare_amount_sum_chunk += data_chunk['fare_amount'].sum() memory_timestep_2 = psutil.virtual_memory() memory_used_pd = (memory_timestep_2[3] - memory_timestep_1[3])/(1024*1024) print("Memory acquired with chunking the dataframe: %.4f MB"%memory_used_pd) # Loading the training dataset using pandas memory_timestep_3 = psutil.virtual_memory() training_data_pd = pd.read_csv("dataset/train_2015.csv") fare_amount_sum_pd = training_data_pd['fare_amount'].sum() memory_timestep_4 = psutil.virtual_memory() memory_used_pd = (memory_timestep_4[3] - memory_timestep_3[3])/(1024*1024) print("Memory acquired without chunking the dataframe: %.4f MB"%memory_used_pd) </code></pre> <pre><code class="language-py">Memory acquired with chunking the dataframe: 103.0469 MB Memory acquired without chunking the dataframe: 854.8477 MB </code></pre> <h3 id="2删除列">2.删除列</h3> <p>有时,我们只需要列的子集,而不是所有的列来进行分析。数据集中存在许多不需要的列。因此,我们将通过使用名为<code>usecols</code>的<code>read_csv()</code>中的参数,只将一些有用的列加载到内存中。</p> <pre><code class="language-py">import pandas as pd import psutil # Loading the training dataset by chunking dataframe memory_timestep_1 = psutil.virtual_memory() columns = ['fare_amount', 'trip_distance'] data_1 = pd.read_csv("dataset/train_2015.csv", usecols=columns) memory_timestep_2 = psutil.virtual_memory() memory_used_pd = (memory_timestep_2[3] - memory_timestep_1[3])/(1024*1024) print("Memory acquired by sampling columns: %.4f MB"%memory_used_pd) # Loading the training dataset using pandas memory_timestep_3 = psutil.virtual_memory() data_2 = pd.read_csv("dataset/train_2015.csv") memory_timestep_4 = psutil.virtual_memory() memory_used_pd = (memory_timestep_4[3] - memory_timestep_3[3])/(1024*1024) print("Memory acquired without sampling columns: %.4f MB"%memory_used_pd) </code></pre> <pre><code class="language-py">Memory acquired by sampling columns: 25.7812 MB Memory acquired without sampling columns: 896.5195 MB </code></pre> <h3 id="3选择正确的数据类型">3.选择正确的数据类型</h3> <p>pandas 为值使用的默认数据类型不是最有效的内存。我们可以根据一些列存储的值来更改它们的数据类型,从而可以在内存中加载大型数据集。</p> <p>例如,我们的数据集包含列 VendorID,它只取值 1 和 2。但是熊猫用的型号是 int64。我们可以把它转换成一个布尔值,这样可以减少存储空间。此外,我们将把列 pick up _ latitude pick up _ longitude、dropoff_latitude、dropoff_longitude 从 float64 转换为 float32,并将 payment_type 转换为 categorical。</p> <pre><code class="language-py">import pandas as pd from sys import getsizeof data = pd.read_csv("dataset/train_2015.csv") size = getsizeof(data)/(1024*1024) print("Initial Size: %.4f MB"%size) # chaning VendorID to boolean data.VendorID = data.VendorID.apply(lambda x: x==2) # chaning pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude to float32 location_columns = ['pickup_latitude','pickup_longitude', 'dropoff_latitude','dropoff_longitude'] data[location_columns] = data[location_columns].astype('float32') # chaning payment_type to categorical data.payment_type = data.payment_type.astype('category') size = getsizeof(data)/(1024*1024) print("Size after reduction: %.4f MB"%size) </code></pre> <pre><code class="language-py">Initial Size: 957.8787 MB Size after reduction: 873.8545 MB </code></pre> <h2 id="用-dask-处理大型数据集">用 Dask 处理大型数据集</h2> <p><a href="https://www.dask.org/" target="_blank">Dask</a> 是一个并行计算库,伸缩 <a href="https://www.askpython.com/python-modules/numpy/python-numpy-arrays" target="_blank">NumPy</a> ,pandas, <a href="https://www.askpython.com/python/data-analytics-libraries" target="_blank">scikit</a> 模块,实现快速计算和低内存。它利用了一台机器有多个内核的事实,dask 利用这一事实进行并行计算。</p> <p>我们可以使用 dask 数据帧,它类似于 pandas 数据帧。dask 数据帧由多个较小的 pandas 数据帧组成。对单个 Dask 数据帧的方法调用会产生许多 pandas 方法调用,Dask 知道如何协调一切以获得结果。</p> <p>让我们使用 pandas 和 dask 从 Kaggle 加载 <a href="https://www.kaggle.com/edwinytleung/nyc-yellow-taxi-2015-sample-data" target="_blank">NYC Yellow Taxi 2015 数据集</a>的训练数据集,并使用<code>psutil.virtual_memory()</code>查看内存消耗。</p> <pre><code class="language-py">import pandas as pd import dask.dataframe as ddf import psutil #Loading the training dataset using dask memory_timestep_3 = psutil.virtual_memory() training_data_ddf = ddf.read_csv("dataset/train_2015.csv") memory_timestep_4 = psutil.virtual_memory() memory_used_ddf = (memory_timestep_4[3] - memory_timestep_3[3])/(1024*1024) print("Memory acquired using dask: %.4f MB"%memory_used_ddf) # Loading the training dataset using pandas memory_timestep_1 = psutil.virtual_memory() training_data_pd = pd.read_csv("dataset/train_2015.csv") memory_timestep_2 = psutil.virtual_memory() memory_used_pd = (memory_timestep_2[3] - memory_timestep_1[3])/(1024*1024) print("Memory acquired using pandas: %.4f MB"%memory_used_pd) </code></pre> <pre><code class="language-py">Memory acquired using dask: 5.1523 MB Memory acquired using pandas: 832.1602 MB </code></pre> <p>dask 和 pandas 数据帧之间的一个主要区别是 dask 数据帧操作是懒惰的。操作不会像 pandas 那样立即执行,而是由 dask 生成任务图,并在需要时读取值。使用完这些值后,它们会被从内存中丢弃,这就是 dask 处理不适合内存的数据的原因。</p> <h2 id="图像数据发生器">图像数据发生器</h2> <p>如果您正在处理占用大量磁盘内存并且无法同时加载到内存中的图像,您可以使用 Keras <code>ImageDataGenerator</code>直接从磁盘批量加载图像。</p> <p>不仅如此,它还为您提供了图像增强的能力,您可以使用旋转、缩放、翻转等方式变换图像,而无需创建新图像,这有助于您为 ML 项目生成多样化的数据集。</p> <p>有一种标准的方法可以让你的数据集目录结构适合使用<code>ImageDataGenerator</code>。您的训练数据集目录应该包含与您的类同名的子目录。在你的子目录中,存储你的同类图片,图片文件名无关紧要。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f8d540adca1fd252d76b763dcad56d87.png" alt="ImageDataGenerator Directory" loading="lazy"></p> <p>ImageDataGenerator Directory</p> <p>让我们使用来自 Kaggle 的<a href="https://www.kaggle.com/tongpython/cat-and-dog" target="_blank">猫狗数据集</a>,并使用<code>ImageDataGenerator</code>加载它。首先,我们将创建一个 ImageDataGenerator 对象,并使用<code>flow_from_directory()</code>方法加载数据。</p> <pre><code class="language-py">from tensorflow.keras.preprocessing.image import ImageDataGenerator import matplotlib.pyplot as plt # Create object of ImageDataGenerator datagen = ImageDataGenerator( rotation_range=20, # randomly rotate images by 20 degrees horizontal_flip = True # randomly flip images ) # Create generator using flow_from_directory method data_generator = datagen.flow_from_directory( directory = "/content/dataset/training_set/training_set", # specify your dataset directory batch_size=16, # specify the no. of images you want to load at a time ) # load a batch using next images, labels = next(data_generator) nrows = 4 ncols = 4 fig = plt.figure(figsize=(10,10)) for i in range(16): fig.add_subplot(nrows, ncols, i+1) plt.imshow(images[i].astype('uint8')) plt.axis(False) plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/bdf8f83cd6d22b33d86a23e37e115f7e.png" alt="ImageDataGenerator Results" loading="lazy"></p> <p>ImageDataGenerator Results</p> <h2 id="自定义数据生成器">自定义数据生成器</h2> <p>如果以上方法对你都不起作用,而你仍然在寻找一些奇迹发生,这是你可以做的。</p> <p>您可以通过继承<code>[tf.keras.utils.Sequence](https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence)</code>类来定义自己的数据生成器,并拥有完全的控制权。你的类必须实现<code>__getitem__</code>和<code>__len__</code>方法。如果您想在不同时期之间修改数据集,您可以实现<code>on_epoch_end</code>。</p> <p>这样,您可以直接从目录中动态加载数据集,并且只使用所需的内存。你可以在你的<code>model.fit()</code>中使用这个来提供数据集。</p> <pre><code class="language-py">import tensorflow as tf import cv2 import numpy import os import matplotlib.pyplot as plt class CustomDataGenerator(tf.keras.utils.Sequence): def __init__(self, batch_size, dataset_directory): self.batch_size = batch_size self.directory = dataset_directory self.list_IDs = os.listdir(self.directory) # Returns the number of batches to generate def __len__(self): return len(self.list_IDs) // self.batch_size # Return a batch of given index # Create your logic how you want to load your data def __getitem__(self, index): batch_IDs = self.list_IDs[index*self.batch_size : (index+1)*self.batch_size] images = [] for id in batch_IDs: path = os.path.join(self.directory, id) image = cv2.imread(path) image = cv2.resize(image, (100,100)) images.append(image) return images dog_data_generator = CustomDataGenerator( batch_size = 16, dataset_directory = "/content/dataset/training_set/training_set/dogs" ) # get a batch of images images = next(iter(dog_data_generator)) nrows = 4 ncols = 4 fig = plt.figure(figsize=(10,10)) for i in range(16): fig.add_subplot(nrows, ncols, i+1) plt.imshow(images[i].astype('uint8')) plt.axis(False) plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7788a92095dc6ff7cf7566b761616e93.png" alt="Custom Data Generator" loading="lazy"></p> <p>Custom Data Generator</p> <h2 id="结论-32">结论</h2> <p>恭喜你!您现在已经知道了处理大型数据集的不同方法。现在,您可以在您的数据科学和机器学习项目中使用它们,低内存将不再是一个问题。</p> <p>感谢阅读!</p> <h1 id="python-中的手写数字识别">Python 中的手写数字识别</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/handwritten-digit-recognition" target="_blank">https://www.askpython.com/python/examples/handwritten-digit-recognition</a></p> </blockquote> <p>你好,初学者!今天在本教程中,我们将学习如何从 sklearn 数据集中已经可用的 <a href="https://www.askpython.com/python/examples/load-and-plot-mnist-dataset-in-python" target="_blank">MNIST 数据集</a>中识别手写数字。为了识别数字,我们将利用<a href="https://www.askpython.com/python/examples/relu-function" target="_blank">卷积神经网络</a> (CNN)。</p> <p>我们先从了解 CNN 是什么开始。</p> <h2 id="什么是卷积神经网络">什么是卷积神经网络?</h2> <p>CNN 是基于多层感知器的计算任务的最重要的神经网络模型之一。这些模型在图像处理方面表现尤为出色。例如,手写的识别。手写识别是神经网络最基本和最优秀的用途之一。CNN 模型经过多层训练,可以做出正确的预测</p> <h3 id="卷积神经网络用例">卷积神经网络用例</h3> <p>CNN 在图像处理等领域发挥着重要作用。它对探测和预测有很大的影响。它甚至被用于纳米技术,如制造半导体。在这里,它被用来检测材料中的缺陷。如果 CNN 与 <a href="https://www.askpython.com/python/examples/handling-large-datasets-machine-learning" target="_blank">Keras</a> 或 <a href="https://www.askpython.com/python-modules/saving-loading-models-tensorflow" target="_blank">Tensorflow</a> 一起使用,与各种分类算法相比,它给出了最高的准确度。与任何其他数据集相比,CNN 和反向传播架构使 MNIST 数据集具有最高的准确性。通过研究,CNN 每天都在开发新的应用。在德国,提出了使用 CNN 的交通标志识别模型。</p> <h2 id="手写数字识别数据集的加载和准备">手写数字识别数据集的加载和准备</h2> <p>我们将要使用的数据集包含大约<strong>60000 张训练图像</strong>和 <strong>10000 张测试图像</strong>。然后我们将数据分别分成<a href="https://www.askpython.com/python/examples/split-data-training-and-testing-set" target="_blank">训练和测试数据集</a>。</p> <p><code>x_train</code>和<code>x_test</code>包含图像的像素代码,而<code>y_test</code>和<code>y_train</code>包含来自<code>0–9</code>的标签,其代表数字,因为数字可以从 0 到 9 变化。</p> <p>现在,我们需要检查数据集的形状是否可以在 CNN 模型中使用。数据的大小被观察为 <strong>(60000,28,28)</strong> ,这意味着 60000 个大小为 <strong>28×28</strong> <strong>像素</strong>的图像。</p> <p>但是为了使用 Keras API,我们需要一个 4 维数组数据集,因此我们需要将 3 维数据转换成 4 维数据集。</p> <pre><code class="language-py">import tensorflow as tf (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) input_shape = (28, 28, 1) </code></pre> <p>下一步是标准化数据,首先将数据转换为浮点型,然后除以 255(最大 RGB 码–最小 RGB 码)。</p> <pre><code class="language-py">x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 </code></pre> <h2 id="构建模型">构建模型</h2> <p>在本教程中,用户将利用 <strong>Keras API</strong> 来构建模型,为了做到这一点,我们将从 Keras 导入<strong>顺序模型</strong>并添加多层,如下所示:</p> <ol> <li>Conv2D</li> <li>最大池化</li> <li>变平</li> <li>拒绝传统社会的人</li> <li>稠密的</li> </ol> <p>脱落层负责对抗过度拟合,展平层将 2D 阵列展平为 1D 阵列。</p> <pre><code class="language-py">from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D model = Sequential() model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(128, activation=tf.nn.relu)) model.add(Dropout(0.2)) model.add(Dense(10,activation=tf.nn.softmax)) </code></pre> <h2 id="编译和拟合模型"><strong>编译和拟合模型</strong></h2> <p>所以现在我们创造了一个<strong>非优化的空 CNN</strong> 。然后,我们设置一个具有给定的<strong>损失函数</strong>的<strong>优化器</strong>,该优化器利用一个度量,并且通过使用创建的训练数据集来拟合模型。ADAM 优化器优于其他类似的优化器。</p> <pre><code class="language-py">model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x=x_train,y=y_train, epochs=10) </code></pre> <p>培训过程的结果如下。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/95e653d97d39afe01cbce634d1ad67ae.png" alt="Training Result Handwritten Digit Recog" loading="lazy"></p> <p>Training Result Handwritten Digit Recog</p> <p>在使用<code>evaluate</code>函数评估模型时,我们观察到<strong>的准确度为 98.4%</strong> 。</p> <h2 id="可视化结果">可视化结果</h2> <p>我们的最后一步是可视化训练模型的结果,并在<code>subplots</code>的帮助下绘制它们。同样的代码和输出如下所示。我们可以看到结果相当准确。</p> <pre><code class="language-py">import matplotlib.pyplot as plt plt.style.use('seaborn') plt.figure(figsize=(10,10)) plt.subplot(4,4,1) image_index = 2853 predict = x_test[image_index].reshape(28,28) pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1)) plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys') plt.title("Predicted Label: "+str(pred.argmax())) plt.subplot(4,4,2) image_index = 2000 predict = x_test[image_index].reshape(28,28) pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1)) plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys') plt.title("Predicted Label: "+str(pred.argmax())) plt.subplot(4,4,3) image_index = 1500 predict = x_test[image_index].reshape(28,28) pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1)) plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys') plt.title("Predicted Label: "+str(pred.argmax())) plt.subplot(4,4,4) image_index = 1345 predict = x_test[image_index].reshape(28,28) pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1)) plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys') plt.title("Predicted Label: "+str(pred.argmax())) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/06a533d2695ed1e539e3a66075431197.png" alt="Handwritten Digit Recog Output" loading="lazy"></p> <p>Handwritten Digit Recog Output</p> <h2 id="结论-33">结论</h2> <p>在本教程中,我们构建了自己的 CNN 集成手写数字识别模型。而且精度出来还挺不错的!</p> <p>感谢您的阅读!</p> <h1 id="python-中的刽子手游戏一步一步的演练">Python 中的刽子手游戏——一步一步的演练</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/hangman-game-in-python" target="_blank">https://www.askpython.com/python/examples/hangman-game-in-python</a></p> </blockquote> <p>在本教程中,我们将学习用 Python 语言创建自己的 hangman 游戏的步骤。</p> <h2 id="关于刽子手">关于刽子手</h2> <p>Hangman 是一种猜谜游戏,玩家的目标是找出隐藏的单词。每一次不正确的猜测都会导致留给玩家的机会减少。</p> <p>剩下的机会以一个绞刑者的形式表现出来。每个英雄的工作就是拯救生命。</p> <hr> <h2 id="python-中-hangman-游戏的演示游戏">Python 中 Hangman 游戏的演示游戏</h2> <p><a href="https://www.askpython.com/wp-content/uploads/2020/06/hangman_game.mp4" target="_blank">https://www.askpython.com/wp-content/uploads/2020/06/hangman_game.mp4</a></p> <hr> <h2 id="设计绞刑">设计绞刑</h2> <p>在我们进入创建游戏逻辑的部分之前,我们首先需要弄清楚游戏对任何玩家来说是什么样子的。这个游戏有两个特别的设计元素:</p> <ul> <li>刽子手–我们需要在刽子手的背景下为玩家提供视觉帮助。</li> <li><strong>单词显示</strong>–在游戏开始时,单词必须显示为空格,而不是字母。</li> </ul> <h3 id="刽子手设计">刽子手设计</h3> <p>我们知道,在每一个不正确的动作之后,被绞死的人身体的一个新的部分被展示出来。为了实现这一点,我们将身体部位存储在一个列表中。</p> <pre><code class="language-py"># Stores the hangman's body values hangman_values = ['O','/','|','\\','|','/','\\'] # Stores the hangman's body values to be shown to the player show_hangman_values = [' ', ' ', ' ', ' ', ' ', ' ', ' '] </code></pre> <p>处理这些 hangman 值的函数如下所示:</p> <pre><code class="language-py"># Functuion to print the hangman def print_hangman(values): print() print("\t +--------+") print("\t | | |") print("\t {} | |".format(values[0])) print("\t{}{}{} | |".format(values[1], values[2], values[3])) print("\t {} | |".format(values[4])) print("\t{} {} | |".format(values[5],values[6])) print("\t | |") print(" _______________|_|___") print(" ``````py```````py```````py`") print() </code></pre> <p>下面的视频显示了游戏中所有可能的刽子手状态。每一个不正确的错误增加一个身体部分,直到身体完整,玩家输。</p> <p><a href="https://www.askpython.com/wp-content/uploads/2020/06/hangman_print_all.mp4" target="_blank">https://www.askpython.com/wp-content/uploads/2020/06/hangman_print_all.mp4</a></p> <p>视频中显示的最终状态代表了玩家猜出完整单词后,刽子手逃离绞刑架。</p> <pre><code class="language-py"># Function to print the hangman after winning def print_hangman_win(): print() print("\t +--------+") print("\t | |") print("\t | |") print("\t O | |") print("\t/|\\ | |") print("\t | | |") print(" ______/_\\______|_|___") print(" ``````py```````py```````py`") print() </code></pre> <p>上面的函数,<code>'print_hangman_win()'</code>负责在玩家获胜时打印逃跑的刽子手。</p> <h3 id="文字显示">文字显示</h3> <p>在游戏开始时,只有空白必须是可见的。在每个玩家输入之后,我们必须处理需要显示的内容。</p> <pre><code class="language-py"># Stores the letters to be displayed word_display = [] </code></pre> <p>最初,列表<code>'word_display'</code>包含隐藏单词中每个字母的下划线。以下函数用于显示该列表。</p> <pre><code class="language-py"># Function to print the word to be guessed def print_word(values): print() print("\t", end="") for x in values: print(x, end="") print() </code></pre> <hr> <h2 id="单词数据集">单词数据集</h2> <p>在创造游戏的这一部分,我们可以让我们的想象力自由驰骋。可以有多种方式访问列表单词,如从<strong>导入。csv</strong> 文件,从数据库中提取等。</p> <p>为了使本教程简单,我们将硬编码一些类别和单词。</p> <pre><code class="language-py"># Types of categories topics = {1: "DC characters", 2:"Marvel characters", 3:"Anime characters"} # Words in each category dataset = {"DC characters":["SUPERMAN", "JOKER", "HARLEY QUINN", "GREEN LANTERN", "FLASH", "WONDER WOMAN", "AQUAMAN", "MARTIAN MANHUNTER", "BATMAN"],\ "Marvel characters":["CAPTAIN AMERICA", "IRON MAN", "THANOS", "HAWKEYE", "BLACK PANTHER", "BLACK WIDOW"], "Anime characters":["MONKEY D. LUFFY", "RORONOA ZORO", "LIGHT YAGAMI", "MIDORIYA IZUKU"] } </code></pre> <p>让我们理解这里使用的数据结构:</p> <ul> <li><code>**'topics'**</code>–这个 Python 字典为每个类别提供了一个数值。这将进一步用于实现一个基于类别的菜单。</li> <li><code>**'dataset'**</code>–这个 Python 字典包含了每个类别的单词列表。当玩家选择一个类别后,我们应该从这里自己选择单词。</li> </ul> <hr> <h2 id="游戏循环">游戏循环</h2> <p>每一个依赖于玩家一系列移动的游戏都需要一个游戏循环。这个循环负责管理玩家输入,显示游戏设计,以及游戏逻辑的其他重要部分。</p> <pre><code class="language-py"># The GAME LOOP while True: </code></pre> <p>在这个游戏循环中,我们将处理以下事情:</p> <hr> <h2 id="游戏菜单">游戏菜单</h2> <p>游戏菜单负责向玩家提供游戏控制的概念。玩家根据他/她的兴趣决定类别。</p> <pre><code class="language-py"># Printing the game menu print() print("-----------------------------------------") print("\t\tGAME MENU") print("-----------------------------------------") for key in topics: print("Press", key, "to select", topics[key]) print("Press", len(topics)+1, "to quit") print() </code></pre> <p>每当创建游戏菜单时,总是提供退出游戏的选项是明智的。</p> <hr> <h2 id="处理玩家的类别选择">处理玩家的类别选择</h2> <p>一个游戏开发人员,不管他的技术水平如何,都必须时刻关注玩家的输入。游戏不能因为一些错误的玩家输入而崩溃。</p> <pre><code class="language-py"># Handling the player category choice try: choice = int(input("Enter your choice = ")) except ValueError: clear() print("Wrong choice!!! Try again") continue # Sanity checks for input if choice > len(topics)+1: clear() print("No such topic!!! Try again.") continue # The EXIT choice elif choice == len(topics)+1: print() print("Thank you for playing!") break </code></pre> <p>在做了一些健全的检查之后,我们已经准备好为游戏选择一个词了。</p> <blockquote> <p><strong>注:</strong><code>'clear()'</code>功能负责清空终端。它利用了 Python 内置的<code>'os'</code>库。</p> </blockquote> <hr> <h2 id="选择游戏用词">选择游戏用词</h2> <p>我们使用内置的 Python 库<code>'random'</code>从特定的类别列表中随机选择一个单词。</p> <pre><code class="language-py"># The topic chosen chosen_topic = topics[choice] # The word randomly selected ran = random.choice(dataset[chosen_topic]) # The overall game function hangman_game(ran) </code></pre> <p>在选择这个词之后,是游戏逻辑部分。</p> <hr> <h2 id="刽子手的游戏逻辑">刽子手的游戏逻辑</h2> <p>功能<code>'hangman()'</code>包含整个游戏功能。包括存储不正确的猜测,减少剩下的机会数,打印刽子手的具体状态。</p> <pre><code class="language-py"># Function for each hangman game def hangman_game(word): clear() # Stores the letters to be displayed word_display = [] # Stores the correct letters in the word correct_letters = [] # Stores the incorrect guesses made by the player incorrect = [] # Number of chances (incorrect guesses) chances = 0 # Stores the hangman's body values hangman_values = ['O','/','|','\\','|','/','\\'] # Stores the hangman's body values to be shown to the player show_hangman_values = [' ', ' ', ' ', ' ', ' ', ' ', ' '] </code></pre> <p>上面的代码片段包含了 hangman 游戏顺利运行所需的所有基本数据结构和变量。</p> <hr> <h2 id="初始化必要的组件">初始化必要的组件</h2> <p>创建游戏最重要的一个方面是游戏组件的初始状态。</p> <pre><code class="language-py"># Loop for creating the display word for char in word: if char.isalpha(): word_display.append('_') correct_letters.append(char.upper()) else: word_display.append(char) </code></pre> <p>我们需要初始化单词显示的结构,因为它会随着游戏中每隔一个单词而变化。为了方便起见,我们在同一个循环中初始化容器来存储正确的字母。</p> <blockquote> <p><strong>注:</strong>我们版本的刽子手游戏只支持字母的猜测。如果读者想要添加猜测其他元素(如数字或特殊字符)的功能,必须在这里进行更改。</p> </blockquote> <hr> <h2 id="内部游戏循环">内部游戏循环</h2> <p>这个内部游戏循环负责控制刽子手游戏的单个游戏流程。它包括显示正确的显示,处理字符输入,更新必要的数据结构,以及游戏的其他关键方面。</p> <pre><code class="language-py"># Inner Game Loop while True: # Printing necessary values print_hangman(show_hangman_values) print_word(word_display) print() print("Incorrect characters : ", incorrect) print() </code></pre> <hr> <h2 id="玩家的移动输入">玩家的移动输入</h2> <p>我们游戏的这一部分处理玩家与我们游戏的交互。在游戏逻辑中实现之前,输入必须检查几个场景:</p> <ul> <li><strong>有效长度</strong>–因为我们接受单个字符,我们需要检查以防玩家恶意输入多个字符。</li> <li>一个字母表?如前所述,我们的刽子手游戏版本只支持猜字母。</li> <li>已经试过了,作为一个体贴的程序员,如果玩家输入了一个不正确的已经试过的字母,我们必须通知他。</li> </ul> <pre><code class="language-py"># Accepting player input inp = input("Enter a character = ") if len(inp) != 1: clear() print("Wrong choice!! Try Again") continue # Checking whether it is a alphabet if not inp[0].isalpha(): clear() print("Wrong choice!! Try Again") continue # Checking if it already tried before if inp.upper() in incorrect: clear() print("Already tried!!") continue </code></pre> <hr> <h2 id="管理玩家的移动">管理玩家的移动</h2> <p>很明显,在管理玩家的移动时,我们只会遇到两种情况。</p> <ul> <li><strong>不正确的字母</strong>–对于不正确的移动,我们更新不正确字母的列表和刽子手显示(添加身体部位)。</li> </ul> <pre><code class="language-py"># Incorrect character input if inp.upper() not in correct_letters: # Adding in the incorrect list incorrect.append(inp.upper()) # Updating the hangman display show_hangman_values[chances] = hangman_values[chances] chances = chances + 1 # Checking if the player lost if chances == len(hangman_values): print() clear() print("\tGAME OVER!!!") print_hangman(hangman_values) print("The word is :", word.upper()) break </code></pre> <ul> <li><strong>正确的字母表</strong>–如果有能力的玩家输入了正确的字母表,我们会更新单词显示。</li> </ul> <pre><code class="language-py"># Correct character input else: # Updating the word display for i in range(len(word)): if word[i].upper() == inp.upper(): word_display[i] = inp.upper() # Checking if the player won if check_win(word_display): clear() print("\tCongratulations! ") print_hangman_win() print("The word is :", word.upper()) break </code></pre> <p>游戏开发者最感兴趣的是每次输入正确的字母时都检查是否获胜。这不是一个硬性的规则,读者可以实现他们自己版本的最终游戏检查。</p> <hr> <h2 id="完整的代码">完整的代码</h2> <p>下面是上面讨论的 hangman 游戏的完整运行代码:</p> <pre><code class="language-py">import random import os # Funtion to clear te terminal def clear(): os.system("clear") # Functuion to print the hangman def print_hangman(values): print() print("\t +--------+") print("\t | | |") print("\t {} | |".format(values[0])) print("\t{}{}{} | |".format(values[1], values[2], values[3])) print("\t {} | |".format(values[4])) print("\t{} {} | |".format(values[5],values[6])) print("\t | |") print(" _______________|_|___") print(" ``````py```````py```````py`") print() # Function to print the hangman after winning def print_hangman_win(): print() print("\t +--------+") print("\t | |") print("\t | |") print("\t O | |") print("\t/|\\ | |") print("\t | | |") print(" ______/_\\______|_|___") print(" ``````py```````py```````py`") print() # Function to print the word to be guessed def print_word(values): print() print("\t", end="") for x in values: print(x, end="") print() # Function to check for win def check_win(values): for char in values: if char == '_': return False return True # Function for each hangman game def hangman_game(word): clear() # Stores the letters to be displayed word_display = [] # Stores the correct letters in the word correct_letters = [] # Stores the incorrect guesses made by the player incorrect = [] # Number of chances (incorrect guesses) chances = 0 # Stores the hangman's body values hangman_values = ['O','/','|','\\','|','/','\\'] # Stores the hangman's body values to be shown to the player show_hangman_values = [' ', ' ', ' ', ' ', ' ', ' ', ' '] # Loop for creating the display word for char in word: if char.isalpha(): word_display.append('_') correct_letters.append(char.upper()) else: word_display.append(char) # Game Loop while True: # Printing necessary values print_hangman(show_hangman_values) print_word(word_display) print() print("Incorrect characters : ", incorrect) print() # Accepting player input inp = input("Enter a character = ") if len(inp) != 1: clear() print("Wrong choice!! Try Again") continue # Checking whether it is a alphabet if not inp[0].isalpha(): clear() print("Wrong choice!! Try Again") continue # Checking if it already tried before if inp.upper() in incorrect: clear() print("Already tried!!") continue # Incorrect character input if inp.upper() not in correct_letters: # Adding in the incorrect list incorrect.append(inp.upper()) # Updating the hangman display show_hangman_values[chances] = hangman_values[chances] chances = chances + 1 # Checking if the player lost if chances == len(hangman_values): print() clear() print("\tGAME OVER!!!") print_hangman(hangman_values) print("The word is :", word.upper()) break # Correct character input else: # Updating the word display for i in range(len(word)): if word[i].upper() == inp.upper(): word_display[i] = inp.upper() # Checking if the player won if check_win(word_display): clear() print("\tCongratulations! ") print_hangman_win() print("The word is :", word.upper()) break clear() if __name__ == "__main__": clear() # Types of categories topics = {1: "DC characters", 2:"Marvel characters", 3:"Anime characters"} # Words in each category dataset = {"DC characters":["SUPERMAN", "JOKER", "HARLEY QUINN", "GREEN LANTERN", "FLASH", "WONDER WOMAN", "AQUAMAN", "MARTIAN MANHUNTER", "BATMAN"],\ "Marvel characters":["CAPTAIN AMERICA", "IRON MAN", "THANOS", "HAWKEYE", "BLACK PANTHER", "BLACK WIDOW"], "Anime characters":["MONKEY D. LUFFY", "RORONOA ZORO", "LIGHT YAGAMI", "MIDORIYA IZUKU"] } # The GAME LOOP while True: # Printing the game menu print() print("-----------------------------------------") print("\t\tGAME MENU") print("-----------------------------------------") for key in topics: print("Press", key, "to select", topics[key]) print("Press", len(topics)+1, "to quit") print() # Handling the player category choice try: choice = int(input("Enter your choice = ")) except ValueError: clear() print("Wrong choice!!! Try again") continue # Sanity checks for input if choice > len(topics)+1: clear() print("No such topic!!! Try again.") continue # The EXIT choice elif choice == len(topics)+1: print() print("Thank you for playing!") break # The topic chosen chosen_topic = topics[choice] # The word randomly selected ran = random.choice(dataset[chosen_topic]) # The overall game function hangman_game(ran) </code></pre> <hr> <h2 id="结论-34">结论</h2> <p>起初,创建刽子手游戏似乎是一项艰巨的任务,但我们希望本教程可以消除读者的误解。如有任何疑问或批评,欢迎在下面评论。</p> <p>如果你想学习更多关于用 Python 开发基于终端的游戏,你可以看看其他游戏,比如<a href="https://www.askpython.com/python/examples/create-minesweeper-using-python" target="_blank">扫雷</a>或者<a href="https://www.askpython.com/python/examples/tic-tac-toe-using-python" target="_blank">井字游戏</a>。</p> <h1 id="python-中的-harshad-数易于实现">Python 中的 Harshad 数–易于实现</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/harshad-number" target="_blank">https://www.askpython.com/python/examples/harshad-number</a></p> </blockquote> <p>你好。今天让我们学习哈沙德数。我们将了解这个数字是什么,然后执行一个程序来检查一个数字是否是一个 Harshad 数字。</p> <h2 id="什么是-harshad-数">什么是 Harshad 数?</h2> <p>如果一个数可以被它的数位之和整除,那么这个数就是 Harshad 数。</p> <p><strong>Harshad 数定义</strong>为:abcd 可被(a+b+c+d)整除。</p> <p><em><strong>推荐阅读:<a href="https://www.askpython.com/python/examples/armstrong-number" target="_blank">如何在 Python 中检查阿姆斯特朗数?</a></strong></em></p> <h2 id="哈沙德数的例子">哈沙德数的例子</h2> <h3 id="示例-1-155">示例 1: 155</h3> <p>数字之和= 1 + 5 + 5 = 11</p> <p>但是 155 不能被 11 整除。因此,这个数字不是一个苛刻的数字。</p> <h3 id="示例-2-156">示例 2: 156</h3> <p>数字之和= 1 + 5 + 6 = 12</p> <p>但是 156 能被 12 整除。因此,这个数字是一个苛刻的数字。</p> <h2 id="检查-harshad-数的算法">检查 Harshad 数的算法</h2> <p>检查一个号码是否为 Harshad 号码的所有步骤如下:</p> <ol> <li>读取输入的数字</li> <li>将号码复制一份,以便稍后检查结果。</li> <li>创建一个结果变量(设置为 0)</li> <li>创建一个 while 循环来逐个数字地遍历数字。</li> <li>在每一次迭代中,结果逐位递增</li> <li>将数字的副本除以得到的结果。</li> <li>如果一个数被整除,那么它就是一个 Harshad 数,否则它就不是。</li> </ol> <h2 id="harshad-号的伪代码">Harshad 号的伪代码</h2> <p>下面的代码显示了检查数字是否为 Harshad 数字的伪代码:</p> <pre><code class="language-py">READ n MAKE A COPY OF n result=0 CHECK DIGIT BY DIGIT: WHILE n!=0 GET CURRENT DIGIT : digit = n % 10 UPDATE RESULT : result = result + digit TRIM THE LAST DIGIT : n = n / 10 ENDWHILE CHECK FOR HARSHAD NUMBER: IF COPY OF n % result == 0 PRINT "HARSHAD NUMBER" ELSE PRINT "NOT A HARSHAD NUMBER" </code></pre> <h2 id="python-中检查-harshad-数的代码">Python 中检查 Harshad 数的代码</h2> <p>现在我们知道了什么是 Harshad 数以及实现它的步骤,让我们一行一行地实现 Harshad 检查。</p> <h3 id="创建初始变量">创建初始变量</h3> <p>我们首先获取一个输入<code>n</code>并存储该输入的一个副本,这样无论我们如何改变原始数字,我们也将结果初始化为 0。</p> <p>相同的代码如下所示:</p> <pre><code class="language-py">n = input() n=int(n) copy_n=n result = 0 </code></pre> <h3 id="遍历数字并更新结果">遍历数字并更新结果</h3> <p>为了访问每个数字,我们用数字的<code>modulus</code>( mod 10)来提取数字的最后一个数字。下一步是将结果更新为前一个结果和当前数字的和。</p> <p>我们采取的最后一步是将数字除以 10,去掉数字的最后一位。重复相同的过程,直到数字中没有剩余的数字。</p> <p>相同的代码如下所示:</p> <pre><code class="language-py">while(n!=0): digit = n%10 result=result + digit n=int(n/10) </code></pre> <h3 id="检查该号码是否是-harshad-号码">检查该号码是否是 Harshad 号码</h3> <p>最后一步是检查我们之前创建的数字的副本是否能被计算的结果整除。相同的代码如下所示:</p> <pre><code class="language-py">if(copy_n % result == 0): print("Harshad Number!") else: print("Not an Harshad Number!") </code></pre> <h2 id="代码的输出示例">代码的输出示例</h2> <p>现在,我测试了程序的两个输入。两个输出如下所示:</p> <h3 id="数字-1-156">数字 1: 156</h3> <pre><code class="language-py">156 Harshad Number! </code></pre> <h3 id="数字-2-121">数字 2: 121</h3> <pre><code class="language-py">121 Not a Harshad Number! </code></pre> <h2 id="结论-35">结论</h2> <p>恭喜你!您已经成功地学习了 Harshad Number 并实现了它!</p> <p>但是不要就此打住!坚持读书学习!</p> <h1 id="在-python-中实现-hashmaps">在 Python 中实现 HashMaps</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/hashmaps-in-python" target="_blank">https://www.askpython.com/python/examples/hashmaps-in-python</a></p> </blockquote> <p>每当我们试图通过我们的数据实现某种搜索逻辑时,我们都希望它是<em>。对于小程序来说可能不是这样,但是对于具有巨大代码库的大型应用程序来说,运行任何类型的逻辑的搜索、删除或修改时间都应该是最小的。</em></p> <p><em>Python 中的字典用于将数据存储为<strong>键:值</strong>对。他们使用一种叫做<strong>哈希</strong>的技术来执行基于时间的搜索操作,这种操作几乎与字典<strong>的大小无关。</strong></em></p> <p><strong><strong>也读: <a href="https://www.askpython.com/python/dictionary/python-dictionary-dict-tutorial" target="_blank">Python 字典(Dict)教程</a></strong></strong></p> <h2 id="哈希是什么"><em>哈希是什么?</em></h2> <p><em>哈希是一种用于对任何类型的数据进行排序和索引的技术。哈希允许我们获取大量要索引的数据或输入,并使用通常使用称为<strong>哈希函数</strong>的东西创建的键将它们存储在更少的输出空间中,哈希函数本质上是应用于我们的输入数据的某种数学逻辑,产生一个数值。</em></p> <p>*<img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/436828387dcc8caebc2927d2c16d345b.png" alt="The Concept Of Hashing" loading="lazy"></p> <p>The Concept Of Hashing*</p> <p><em>假设我们有三个字符串,我们想用一些数学逻辑以一种有效的方式存储它们。这里我们有一串约翰、彼得、T1 和 T2、凯莉和 T3。所以如果你想用散列法存储它们,第一步是我们用散列函数把这些字符串变成一个数字。</em></p> <p><em>如果我们使用哈希函数将这些字符串转换为数字,我们首先将约翰的单词转换为 10,然后将 T2 的彼得的单词转换为 T3。换算成 5。然后我们继续转换<strong>卡丽</strong>,将是 11。因此,我们将字符串转换成了数字。</em></p> <p><em>现在你可能对如何转换感兴趣,这里的<strong>散列函数</strong> 是什么,以及它是如何工作的。我们将在文章中进一步理解这一点。</em></p> <h2 id="python-中的散列函数"><em>Python 中的散列函数</em></h2> <p><strong>哈希函数负责通过使用一些公式将这些字符串转换成数字。</strong></p> <p><em>接下来,我们必须将这些数字存储在一些数据结构中。如果我们有一个数组或 python 列表,其中有 12 个单元格,如此处所示,通过使用这个哈希函数生成的数字,我们将把这些字符串插入到这些数组中。</em></p> <p><em>所以对于第一串,也就是约翰,我们有 10 个。我们将把<strong>约翰</strong>字符串插入到这个数组中 10 个 的 <em><strong>索引中。然后,下一串是</strong>彼得</em>*。所以当我们把它转换成数字时,它就变成了 5。</em>***</p> <p><em>我们将把<strong>彼得</strong>字符串插入到 5T5 的<strong>T3 的索引中。现在,下一个单词是 <strong>Carrie</strong> 。当我们在这里使用哈希函数转换 Carrie 时,它变成了 11。所以我们将把 11 个</strong> 的 <em><strong>索引的 Carrie 插入到这个数组中。我们已经完成了这些字符串到整数的转换,我们正在将这些字符串插入到这个数组中。</strong></em></em></p> <h2 id="使用哈希函数读取或访问数据"><em>使用哈希函数读取或访问数据</em></h2> <p><em>现在的问题是,如果我们想从这个数组中读取数据,我们如何访问它?</em></p> <p><em>同样,逻辑是一样的。例如,如果我们想要访问 <strong>John</strong> ,我们要做的第一件事就是使用相同的哈希函数并将 John 转换为数字。每次我们转换同一个字符串,结果都是一样的。所以我们会得到 10。基于索引 10,我们可以访问这里的元素。</em></p> <h2 id="为什么我们需要散列"><em>为什么我们需要散列?</em></h2> <p><em>我们知道,根据索引访问数组或 Python 列表中的元素需要 <em><strong>O(1)</strong></em> <em><strong>时间复杂度</strong></em> 。这就是为什么在数据结构中搜索一个给定值时散列是非常重要的。这样做,我们可以很容易地识别字符串是否在这个数组中。</em></p> <p><em>假设我们想开发一个应用程序,其中搜索操作被大量使用,我们希望我们的应用程序执行得尽可能快。在这种情况下,我们可以使用散列法。就搜索操作而言,散列也比任何其他数据结构表现得更好。</em></p> <h2 id="哈希术语"><em>哈希术语</em></h2> <ul> <li><em><strong>哈希函数</strong>:它是一种逻辑或数学公式,可以用来将任意大小的输入数据映射为固定大小或更小大小的输出。</em></li> <li><em><strong>散列值</strong>:散列函数返回的值。</em></li> <li><em><strong>哈希表</strong>:是实现关联数组抽象数据类型的数据结构,也是可以将键映射到值的结构。</em></li> <li><em><strong>冲突</strong>:当散列函数的两个不同键产生相同的输出时,就会发生冲突。</em></li> </ul> <h2 id="用-python-实现散列表"><em>用 Python 实现散列表</em></h2> <p><em>让我们通过实现一个 Hashmap 来了解它的概况。我们将创建一个包含基本函数的自定义类。下面是我们的自定义类中包含的函数。代码本身包含了我们在文章前面讨论过的所有解释。</em></p> <ul> <li><em><strong>_hash( <em>self</em> , <em>key</em> ):</strong> 这是我们定义的哈希函数或者数学逻辑,我们应用到 key 上,把它转换成整数值。</em></li> <li><em><strong><em>set</em> ( <em>self</em> , <em>key</em> , <em>value</em> ):</strong> 这个函数允许我们将一个 key | value 对添加到我们的 Hash Map 中。</em></li> <li><em><strong>get( <em>self</em> , <em>key</em> )</strong> :为了检索给定 key 的值,使用该函数。</em></li> <li><em><strong><strong>str</strong>( <em>self</em> ):</strong> 将完整的 Hash 图打印到我们的终端。</em></li> </ul> <h5 id="密码"><em>密码</em></h5> <pre><code class="language-py">*class HashMap(object): def __init__(self, size): """Initializing the list with the argument size for our HashMap""" self.data = [[]] * (size) def _hash(self, key): """Hash Function: marked as a private method in the Object""" # Initialize hash_value = 0 # Iterating and generating hashed values using the logic below # Logic: Taking the initial value of 0 and adding to it the ASCII encoding for each character, # and multiplying by the index value. After that we are taking the modulus of the result using the # length of the array # This becomes our hashed value i.e. the index position of the input to be placed # in the output space for i in range(len(key)): hash_value = (hash_value + ord(key[i]) * i) % len(self.data) return hash_value def set(self, key, value): # Represents the index position where we want to store our data address = self._hash(key) if not self.data[address]: self.data[address] = [] # If there is a collision of index value i.e. our hashed value # then simply add on to that array self.data[address].append([key, value]) return self.data def get(self, key): # Getting the hashed value again, with the same hash function to locate the value # for the given key address = self._hash(key) # assigning the entire array to a variable in-order to operate later currentBucket = self.data[address] if currentBucket: # Iterating over the entire list to get the value for i in range(len(currentBucket)): # Check to retrieve the value if currentBucket[i][0] == key: # If found, return the current bucket return currentBucket[i][1] # If no value present return "Data Not Found" # In order to print the hashmap to see the structure def __str__(self): return "".join(str(item) for item in self.data) # Instantiating from our Object Class with 50 buckets myHash = HashMap(50) # Setting the values to the hash table myHash.set("john", 123) myHash.set("peter", 567) myHash.set("carrie", 898) # Printing the entire hash table print(myHash) # Getting the values from the hash table using the keys print(myHash.get("john")) # Output: 123 print(myHash.get("guava")) # Output: Data Not Found* </code></pre> <h5 id="输出"><em>输出</em></h5> <p>*<img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/60261ce21bd345e9b904641f06b5271a.png" alt="Generated HashMap" loading="lazy"></p> <p>Generated HashMap*</p> <h2 id="结论-36"><em>结论</em></h2> <p><em>在本文中,我们讨论了使用 Python 创建散列图的关键术语和方法。顾名思义,这就像使用数据创建一个地图,在底层逻辑上提供一个抽象来表示。它们提供了一种基于键显示和定位值以及基于键插入和删除值的有效方法。</em></p> <h1 id="python-中的-hcf-和-lcm使用-python-计算-hcf-和-lcm">Python 中的 HCF 和 LCM–使用 Python 计算 HCF 和 LCM</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/hcf-and-lcm-in-python" target="_blank">https://www.askpython.com/python/examples/hcf-and-lcm-in-python</a></p> </blockquote> <p>嘿程序员朋友!今天在本教程中,我们将学习如何使用 python 编程语言计算最高公因数(HCF)和最低公倍数(LCM)。</p> <p>让我们先了解一下我们所说的两个数的 HCF 和 LCM 是什么意思,如果你现在还不熟悉这些术语的话。</p> <p><em><strong>也读作:<a href="https://www.askpython.com/python/examples/calculating-precision" target="_blank">Python 中的计算精度—分类误差度量</a></strong></em></p> <hr> <h2 id="什么是最高公因数">什么是最高公因数?</h2> <p>两个数的最大公因数定义为两个数的最大公因数。例如,让我们考虑两个数字 12 和 18。</p> <p>提到的这两个数字的公因数是 2、3 和 6。三者中最高的是 6。在这种情况下,HCF 是 6。</p> <hr> <h2 id="什么是最低公共乘数">什么是最低公共乘数?</h2> <p>两个数的最小/最低公倍数叫做两个数的最低公倍数。例如,让我们再次考虑 12 和 18 这两个数字。</p> <p>这两个数字的乘数可以是 36、72、108 等等。但是我们需要最低的公共乘数,所以 12 和 18 的 LCM 是 36。</p> <hr> <h2 id="用-python-计算-hcf-和-lcm">用 Python 计算 HCF 和 LCM</h2> <p>让我们开始用 Python 代码实现 HCF 和 LCM。</p> <h3 id="1求两个数的-hcf">1.求两个数的 HCF</h3> <pre><code class="language-py">a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) HCF = 1 for i in range(2,a+1): if(a%i==0 and b%i==0): HCF = i print("First Number is: ",a) print("Second Number is: ",b) print("HCF of the numbers is: ",HCF) </code></pre> <p>让我们传递两个数字作为输入,看看我们的结果是什么。</p> <pre><code class="language-py">First Number is: 12 Second Number is: 18 HCF of the numbers is: 6 </code></pre> <h3 id="2求两个数的-lcm">2.求两个数的 LCM</h3> <p>在我们计算了这两个数字的 HCF 之后,找到 LCM 并不是一件困难的事情。LCM 简单地等于数的乘积除以数的 HCF。</p> <pre><code class="language-py">a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) HCF = 1 for i in range(2,a+1): if(a%i==0 and b%i==0): HCF = i print("First Number is: ",a) print("Second Number is: ",b) LCM = int((a*b)/(HCF)) print("LCM of the two numbers is: ",LCM) </code></pre> <p>让我们传递这两个数字,看看结果是什么。</p> <pre><code class="language-py">First Number is: 12 Second Number is: 18 LCM of the two numbers is: 36 </code></pre> <hr> <h2 id="结论-37">结论</h2> <p>我希望你现在清楚了两个数的 HCF 和 LCM 的计算。我想你也已经了解了 python 编程语言中的相同实现。</p> <p>感谢您的阅读!快乐学习!😇</p> <hr> <h1 id="获得熊猫数据帧或系列的头部和尾部">获得熊猫数据帧或系列的头部和尾部</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/pandas/head-and-tail-of-dataframe-series" target="_blank">https://www.askpython.com/python-modules/pandas/head-and-tail-of-dataframe-series</a></p> </blockquote> <p>在本 Python 教程中,我们将讨论获得熊猫数据帧或系列对象的头部和尾部的不同方法。所以让我们开始吧。</p> <hr> <h2 id="为什么要得到熊猫的头部和尾部">为什么要得到熊猫的头部和尾部?</h2> <p>我们都知道 <strong><a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">Pandas</a></strong> 是一个必不可少的 Python 库,广泛用于数据分析。众所周知,数据分析处理非常大的数据集。因此,为了快速浏览大样本数据集(以 pandas DataFrame 或 Series 对象的形式加载),我们需要 pandas DataFrame 或 Series 的头部和尾部。</p> <p>我们主要使用 pandas DataFrame 类的<code>DataFrame.head()</code>和<code>DataFrame.tail()</code>函数来分别获取 pandas DataFrame 或系列的第一行和最后一行<code>N</code>(默认情况下是这个 <strong>N</strong> = 5 的值)。</p> <h2 id="熊猫数据帧的头部和尾部">熊猫数据帧的头部和尾部</h2> <p>因此,在继续讨论熊猫数据帧对象的头部和尾部之前,让我们创建一个样本熊猫数据帧对象。</p> <h3 id="创建一个示例-pandas-dataframe-对象">创建一个示例 pandas DataFrame 对象</h3> <pre><code class="language-py"># Import pandas Python module import pandas as pd # Create a large pandas DataFrame object df = pd.DataFrame({'RegNo': [111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125], 'Dept': ['ECE', 'ICE', 'IT', 'CSE', 'CHE', 'EE', 'ME', 'CSE', 'ICE', 'TT', 'ECE', 'IT', 'ME', 'BT', 'EE']}) # Print the created pandas DataFrame print('Sample pandas DataFrame:\n') print(df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Sample pandas DataFrame: RegNo Dept 0 111 ECE 1 112 ICE 2 113 IT 3 114 CSE 4 115 CHE 5 116 EE 6 117 ME 7 118 CSE 8 119 ICE 9 120 TT 10 121 ECE 11 122 IT 12 123 ME 13 124 BT 14 125 EE </code></pre> <h3 id="得到熊猫的头像数据帧熊猫dataframehead">得到熊猫的头像数据帧:熊猫。DataFrame.head()</h3> <pre><code class="language-py"># Get the head of the sample pandas Series print('First 10 rows of the sample pandas DataFrame:\n') temp_df = df.head(10) print(temp_df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">First 10 rows of the sample pandas DataFrame: RegNo Dept 0 111 ECE 1 112 ICE 2 113 IT 3 114 CSE 4 115 CHE 5 116 EE 6 117 ME 7 118 CSE 8 119 ICE 9 120 TT </code></pre> <h3 id="得到熊猫的尾巴数据帧熊猫dataframetail">得到熊猫的尾巴数据帧:熊猫。DataFrame.tail()</h3> <pre><code class="language-py"># Get the tail of the sample pandas Series print('Last 10 rows of the sample pandas DataFrame:\n') temp_df = df.tail(10) print(temp_df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Last 10 rows of the sample pandas DataFrame: RegNo Dept 5 116 EE 6 117 ME 7 118 CSE 8 119 ICE 9 120 TT 10 121 ECE 11 122 IT 12 123 ME 13 124 BT 14 125 EE </code></pre> <h3 id="将熊猫数据帧的头部和尾部放在一起pandasoption_context">将熊猫数据帧的头部和尾部放在一起:pandas.option_context()</h3> <pre><code class="language-py"># Get the head and tail of the sample pandas DataFrame # Using the pd.option_context() function in Pandas print('First and Last 5 rows of the sample pandas DataFrame:\n') with pd.option_context('display.max_rows',10): print(df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">First and Last 5 rows of the sample pandas DataFrame: RegNo Dept 0 111 ECE 1 112 ICE 2 113 IT 3 114 CSE 4 115 CHE .. ... ... 10 121 ECE 11 122 IT 12 123 ME 13 124 BT 14 125 EE [15 rows x 2 columns] </code></pre> <h2 id="熊猫系列的头尾">熊猫系列的头尾</h2> <p>因此,在继续讨论熊猫系列对象的头部和尾部之前,让我们创建一个熊猫系列对象的样本。</p> <h3 id="创建一个示例熊猫系列对象">创建一个示例熊猫系列对象</h3> <pre><code class="language-py"># Import pandas Python module import pandas as pd # Import NumPy Python module import numpy as np # Create a pandas Series sr = pd.Series(np.random.randn(1000)) # Print the created pandas Series print('Sample pandas Series:\n') print(sr) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Sample pandas Series: 0 -0.157775 1 -0.108095 2 -0.876501 3 -0.591994 4 -0.435755 ... 995 1.186127 996 -0.898278 997 -0.267392 998 1.295608 999 -2.024564 Length: 1000, dtype: float64 </code></pre> <h3 id="得到一个熊猫系列的头熊猫serieshead">得到一个熊猫系列的头:熊猫。Series.head()</h3> <pre><code class="language-py"># Get the head of the sample pandas Series print('First 10 values of the sample pandas Series:\n') temp_sr = sr.head(10) print(temp_sr) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">First 10 values of the sample pandas Series: 0 -0.157775 1 -0.108095 2 -0.876501 3 -0.591994 4 -0.435755 5 -1.204434 6 -0.035977 7 0.015345 8 -0.453117 9 -0.695302 dtype: float64 </code></pre> <h3 id="得到一个熊猫系列的尾巴熊猫seriestail">得到一个熊猫系列的尾巴:熊猫。Series.tail()</h3> <pre><code class="language-py"># Get the tail of the sample pandas Series print('Last 10 values of the sample pandas Series:\n') temp_sr = sr.tail(10) print(temp_sr) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Last 10 values of the sample pandas Series: 990 -0.239336 991 -1.475996 992 -0.162860 993 0.405505 994 0.458872 995 1.186127 996 -0.898278 997 -0.267392 998 1.295608 999 -2.024564 dtype: float64 </code></pre> <h2 id="总结-1">总结</h2> <p>在这个 Python 教程中,我们已经学习了如何使用<code>head()</code>和<code>tail()</code>函数获得熊猫数据帧或系列的头部和尾部。我们还看到了如何在 pandas 中使用<code>pandas.option_context()</code>功能同时获得熊猫数据帧的头部和尾部。希望您已经理解了上面讨论的内容,并对使用熊猫功能快速浏览您的大熊猫数据框架感到兴奋。感谢阅读!请继续关注我们,获取更多关于 Python 编程的学习资源。</p> <h1 id="python-中的堆">Python 中的堆</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/heaps-in-python" target="_blank">https://www.askpython.com/python/examples/heaps-in-python</a></p> </blockquote> <p>在本文中,我们将了解一个重要的数据结构,Python 中的堆(Python 中称为堆队列)。我们将学习数据结构及其实现,然后查看 Python 代码。</p> <h2 id="python-中的堆是什么"><strong>Python 中的堆是什么</strong>?</h2> <p>Python 中的堆是完整的<a href="https://www.askpython.com/python/examples/binary-tree-implementation" target="_blank">二叉树</a>,其中每个节点或者小于等于或者大于等于它的所有子节点(小于或大于取决于它是最大堆还是最小堆)。</p> <p>因此,堆的根节点要么是最小的,要么是最大的元素。<strong>堆数据结构一般用来表示优先级队列</strong>。</p> <p>通常,堆有两种形式:</p> <ul> <li>最小堆(Min-Heap):最小堆是指所有节点都小于其子节点的堆。根包含最小堆中的最低值。</li> <li><strong>Max-Heap</strong> : Max heap 是所有节点大于其子节点的堆。根包含最大堆中的最高值。</li> </ul> <p>以下是最小堆和最大堆的示例。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f8eb141e5bc0b411addf9ae04bfaa06f.png" alt="Heap Python AskPython Content 1" loading="lazy"></p> <p>Heap in Python</p> <p>默认情况下,Python 中的堆是最小堆,在本文的后面,当我们讨论堆时,我们将考虑最小堆。现在让我们看看堆数据结构是如何实际实现的。</p> <h2 id="python-中堆是如何表示的">Python 中堆是如何表示的?</h2> <p>堆数据结构理论上是二叉树的形式,但是由于其完整性(其中除了最后一层中最右边的节点之外,树是完整的),堆以<a href="https://www.askpython.com/python/array/python-array-declaration" target="_blank">数组</a>的形式存储在存储器中。第一个元素包含最小元素(在 min-heap 的情况下)。</p> <p>树形式的堆存储在数组中,其元素按以下方式进行索引:</p> <ul> <li>根元素将位于数组的第 0 个位置,即 Heap[0]。</li> <li>对于任何其他节点,比如说 Heap[i],我们有以下内容: <ul> <li>父节点由:Heap[(i -1) / 2]给出。</li> <li>左边的子节点由下式给出:Heap[(2 * i) + 1]</li> <li>右边的子节点由下式给出:Heap[(2 * i) + 2]</li> </ul> </li> </ul> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fe65e0e8c59a1f31fd049afbd8147a8c.png" alt="Heap Python AskPython Content 2 1" loading="lazy"></p> <p>Heap Python Array index Representation</p> <h2 id="使用-heapq-模块在-python-中实现堆"><strong>使用 heapq 模块在 Python 中实现堆</strong></h2> <p>Python 有<a href="https://www.askpython.com/python-modules/python-heapq-module" target="_blank">“heapq”模块</a>用于堆队列(或简称堆)的实现。它包含的功能是最小的元素总是在顶部,当调用 pop 函数时会弹出。</p> <p>每当元素被压入或弹出时,堆属性将被保持,heap[0]将总是给我们最小的函数。</p> <p>该模块包含堆的以下主要功能:</p> <ul> <li>heap ify(iterable _ name):我们使用这个函数来传递任何 iterable(例如一个列表),它将它转换成一个堆数据结构。</li> <li><strong>heappush</strong> ( heap_name,element_to_be_inserted):顾名思义,这个函数向堆中推送/添加一个元素。我们需要传递堆名和要作为参数插入的元素。该函数负责重新排列堆(如果需要的话)以满足堆属性。</li> <li><strong>heappop</strong> ( heap_name):顾名思义,这个函数从作为参数传递的堆中弹出/移除一个元素。该函数负责重新排列堆(如果需要的话)以满足堆属性。</li> </ul> <h2 id="python-堆的实际实现">Python 堆的实际实现</h2> <p>现在,我们将在 Python 中实现一个 min-heap。我们在代码中使用了一个 <code>list [15, 7, 9, 4, 13]</code> ,并使用<code>heapify</code>函数将其转换为一个堆。生成的堆将如下所示:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/05661a0bb75030cf3f45fb3446ea0753.png" alt="Heap Python AskPython Content 3 1" loading="lazy"></p> <p>Min heap Example</p> <p><strong>Python 中堆的实现:</strong></p> <pre><code class="language-py"># The heap functionalities are in the heapq package, so import it import heapq # we now initialise a list to be converted to heap lis = [15, 7, 9, 4, 13] # converting lis to heap using the heapify function heapq.heapify(lis) print ("The heap looks like: ") print(lis) #using the heappop function print ("The popped item using heappushpop() is : ",end="") print (heapq.heappop(lis)) print ("After popping, the heap looks like: ") print(lis) #using the heappush function to push 2 print ("After pushing 2, the heap looks like: ") heapq.heappush(lis, 2) print(lis) </code></pre> <p>输出:</p> <pre><code class="language-py">The heap looks like: [4, 7, 9, 15, 13] The popped item using heappop() is : 4 After popping, the heap looks like: [7, 13, 9, 15] After pushing 2, the heap looks like: [2, 7, 9, 15, 13] </code></pre> <p>在这里,我们可以看到 heapq 包提供了创建队列的功能,并向它推送和弹出元素。推送或弹出后,堆会自动重新排列自己,如输出所示。</p> <h2 id="结论-38">结论</h2> <p>在本文中,我们学习了 Python 中堆的概念。我们研究了 Python 中的最大堆和最小堆是什么,以及它们是如何表示的。</p> <p>我们使用<code>heapify</code>、<code>heappush</code>和<code>heappop</code> 函数在 python 中进一步实现了它。请继续关注更多内容丰富的文章。</p> <p>快乐学习!</p> <h1 id="python-中的热图如何用-python-创建热图">Python 中的热图——如何用 Python 创建热图?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/heatmaps-in-python" target="_blank">https://www.askpython.com/python/examples/heatmaps-in-python</a></p> </blockquote> <p>你好。今天,我们将了解 Python 中热图的用法,以及如何为不同的数据集创建热图。</p> <h2 id="什么是热图">什么是热图?</h2> <p>热图利用色调、饱和度或亮度等颜色变化将数据可视化为二维彩色图。热图以颜色而不是数字的形式描述变量之间的关系。</p> <p>这些变量绘制在两个轴上。颜色变化根据特定块中颜色的强度来描述两个值之间的关系。</p> <p>热图有很多应用,下面列出了其中一些:</p> <ol> <li>可视化业务分析</li> <li>探索数据分析</li> <li>探索营销和销售</li> <li>可视化网站或应用程序的访问者数量</li> </ol> <hr> <h2 id="使用热图的行业">使用热图的行业</h2> <p>如今,许多行业都在使用热图。一些行业是:</p> <ul> <li><strong>医疗保健</strong></li> <li><strong>金融</strong></li> <li><strong>技术</strong></li> <li><strong>房地产</strong></li> </ul> <hr> <h2 id="用-python-绘制热图">用 Python 绘制热图</h2> <p>在 python 编程语言中,有多种绘制热图的方法。我们将一个接一个地理解每一种方法。为了方便起见,我们先把这些方法列出来。</p> <ol> <li><strong>使用 Seaborn 库</strong></li> <li><strong>使用 pcolormesh()函数</strong></li> <li><strong>使用 matplotlib.pyplot 库</strong></li> </ol> <h3 id="方法-1使用-seaborn-库">方法 1:使用 Seaborn 库</h3> <p>为了使用 <a href="https://www.askpython.com/python-modules/python-seaborn-tutorial" target="_blank">seaborn 库</a>绘制热图,我们首先需要将所有必要的模块/库导入到我们的程序中。</p> <p>然后,我们生成一个特定大小的“随机矩阵”,然后在<code>heatmap</code>函数的帮助下绘制热图,并将数据集传递给函数。</p> <pre><code class="language-py"># 1\. Import Modules import numpy as np import seaborn as sns import matplotlib.pylab as plt plt.style.use("seaborn") # 2\. Generate a 10x10 random integer matrix data = np.random.rand(10,10) print("Our dataset is : ",data) # 3\. Plot the heatmap plt.figure(figsize=(10,10)) heat_map = sns.heatmap( data, linewidth = 1 , annot = True) plt.title( "HeatMap using Seaborn Method" ) plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/245836110d6fde5c989939df4c4bdff5.png" alt="Heatmap Using Seaborn Heatmaps in Python" loading="lazy"></p> <p>Heatmap Using Seaborn</p> <hr> <h3 id="方法-2使用-pcolormesh-函数">方法 2:使用 pcolormesh 函数</h3> <p>为了使用<code>pcolormesh</code>函数绘制热图,我们首先需要将所有必要的模块/库导入到我们的代码中。</p> <p>我们将使用各种<code>cmaps</code>绘制热图,因此我们将在 matplotlib 中使用<code>subplots</code>。matplotlib 的<code>pcolormesh</code>函数需要数据集,我们可以指定颜色图来绘制热图。</p> <pre><code class="language-py">import matplotlib.pyplot as plt import numpy as np data= np.random.rand(10,10) plt.subplot(2,2,1) plt.pcolormesh(data, cmap = 'rainbow') plt.title('HeatMap Using pcolormesh function') plt.subplot(2,2,2) plt.pcolormesh(data, cmap = 'twilight') plt.title('HeatMap Using pcolormesh function') plt.subplot(2,2,3) plt.pcolormesh(data, cmap = 'summer') plt.title('HeatMap Using pcolormesh function') plt.subplot(2,2,4) plt.pcolormesh(data, cmap = 'winter') plt.title('HeatMap Using pcolormesh function') plt.tight_layout() plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/077a7765a6f330047a2ab850fb58d9c4.png" alt="Heatmap Using Pcolormesh Function Heatmaps in Python" loading="lazy"></p> <p>Heatmap Using Pcolormesh Function</p> <hr> <h3 id="方法三使用-matplotlibpyplot-库">方法三:<strong>使用 matplotlib.pyplot 库</strong></h3> <p>为了使用<code>matplotlib.pyplot</code>库绘制热图,我们首先需要将所有必要的模块/库导入到我们的程序中。</p> <p>就像前面的方法一样,我们将使用各种<code>cmaps</code>绘制热图,因此我们将利用 matplotlib 中的<code>subplots</code>。<code>matplotlib</code>库利用了需要数据集的<code>imshow</code>函数,我们可以指定颜色图来绘制热图。</p> <pre><code class="language-py">import numpy as np import matplotlib.pyplot as plt data= np.random.random((10,10)) plt.subplot(2,2,1) plt.imshow( data, interpolation = 'nearest',cmap="rainbow") plt.title('HeatMap Using Matplotlib Library') plt.subplot(2,2,2) plt.imshow( data, interpolation = 'nearest',cmap="twilight") plt.title('HeatMap Using Matplotlib Library') plt.subplot(2,2,3) plt.imshow( data, interpolation = 'nearest',cmap="summer") plt.title('HeatMap Using Matplotlib Library') plt.subplot(2,2,4) plt.imshow( data, interpolation = 'nearest',cmap="ocean") plt.title('HeatMap Using Matplotlib Library') plt.tight_layout() plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7a40a044be9fc6c625ab868ee4349d75.png" alt="Heatmap Using Matplotlib Library" loading="lazy"></p> <p>Heatmap Using Matplotlib Library</p> <h2 id="结尾词">结尾词</h2> <p>感谢您阅读本教程!我相信我已经介绍了绘制热图的所有方法,现在您可以尝试绘制实时数据!敬请关注更多此类教程!</p> <h1 id="python-hello-world-程序">Python Hello World 程序</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/hello-world" target="_blank">https://www.askpython.com/python/hello-world</a></p> </blockquote> <p>如果您来到这里,我假设您听说过 Python 编程并想学习它。那太好了。学习任何新的编程语言的第一步是编写臭名昭著的 Hello World 程序。</p> <p>让我们编写第一个 Python 程序,在控制台上打印“Hello World”。让我们先来看看这个程序,然后我们将学习 Python 程序是如何工作的。但是,在此之前,我们必须在电脑上安装 Python。</p> <h2 id="下载和安装-python">下载和安装 Python</h2> <p>Python 为不同的操作系统提供了不同的安装程序。因此,安装过程也略有不同,但在任何操作系统上安装 Python 都非常简单快捷。</p> <h3 id="1在-windows-上安装-python">1.在 Windows 上安装 Python</h3> <p>Python 为 Windows 提供了基于 UI 的完整安装程序。进入 <a href="https://www.python.org/downloads/windows/" target="_blank">Python Releases for Windows</a> 页面,从“<strong>稳定版本</strong>部分,下载 <strong>Windows Installer EXE</strong> 文件。只要运行安装程序,它就会在 Windows 中安装 Python。确保选中将 Python 二进制文件夹添加到路径的选项,以节省额外的工作。</p> <h3 id="2在-mac-os-上安装-python">2.在 Mac OS 上安装 Python</h3> <p>转到 <a href="https://www.python.org/downloads/macos/" target="_blank">Python Releases for macOS</a> 页面,从“稳定版本”部分下载 <strong>macOS 64 位 universal2 安装程序</strong>包。运行安装程序,它将在瞬间完成。</p> <h3 id="3在-linuxunix-上安装-python">3.在 Linux/Unix 上安装 Python</h3> <p>大多数 Linux 操作系统都预装了 Python。只需运行“<strong>python 3–version</strong>”命令进行确认并检查版本即可。如果你想使用最新版本,请遵循 Python Docs 上<a href="https://docs.python.org/3/using/unix.html#getting-and-installing-the-latest-version-of-python" target="_blank">这一页的说明。</a></p> <h2 id="我喜欢这里">我喜欢这里</h2> <p>如果你是认真学习 Python 的,PyCharm IDE 是必须的。转到 <a href="https://www.jetbrains.com/pycharm/download/" target="_blank">PyCharm 下载</a>页面,下载适用于您的操作系统的免费社区版本并进行安装。这非常简单,会节省你很多时间。</p> <hr> <h2 id="python-hello-world-程序-1">Python Hello World 程序</h2> <p>现在我们已经在系统中安装了 Python,我们准备编写 Python 程序来打印 Hello World。下面是在控制台上打印“Hello World”的 python 脚本。</p> <pre><code class="language-py">print("Hello World") </code></pre> <p>对,就是这样。没有比这更简单的了。</p> <p>下面是从 PyCharm IDE 中执行这个脚本时的输出。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3040e3762d1d845d1f027eaa89e9a103.png" alt="Python Hello World Program Output" loading="lazy"></p> <p>Python Hello World Program Output</p> <p>这是我们编写的最简单的程序。让我们也从 python 命令行解释器执行它。</p> <pre><code class="language-py">$ cat hello_world.py print("Hello World") $ python3.7 hello_world.py Hello World $ </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/38fadb1c43d932cabaaba5ea77652d6a.png" alt="Python Hello World Program Execute From Terminal" loading="lazy"></p> <p>Python Hello World Program Execute From Terminal</p> <hr> <h2 id="从-python-命令行解释器打印hello-world">从 Python 命令行解释器打印“Hello World”</h2> <p>Python 附带了一个解释器,这是一个类似 shell 的接口,用于运行 python 脚本。让我们看看如何从 python 解释器在控制台上打印“Hello World”消息。</p> <pre><code class="language-py">$ python3.7 Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello World") Hello World >>> </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/becfc69b3570324b0eb2f814c808262b.png" alt="Python Interpreter Hello World Example" loading="lazy"></p> <p>Python Interpreter Hello World Example</p> <hr> <h2 id="了解-python-hello-world-程序">了解 Python Hello World 程序</h2> <ul> <li>print()函数是内置函数之一。该函数将参数打印到控制台。</li> <li>我们用字符串参数“Hello World”调用 print()函数,以便在控制台上打印出来。</li> <li>当我们执行一个 python 脚本文件时,语句被一个接一个地执行。print()语句被执行,它将“Hello World”消息打印到控制台上。</li> </ul> <hr> <h2 id="摘要">摘要</h2> <p>我们从传统的“Hello World”程序开始了学习 Python 编程的旅程。我们在系统中安装了 Python 和 PyCharm IDE。我们了解到 python 程序可以从 PyCharm IDE 和终端执行。我们还对 python 解释器工具有了一些了解,它在运行小的 python 代码片段时非常有用。</p> <h2 id="下一步是什么">下一步是什么?</h2> <p>如果你已经走到这一步,你注定要学习 Python。我建议你接下来浏览这 5 个教程。</p> <ul> <li><a href="https://www.askpython.com/python/python-data-types" target="_blank">Python 数据类型</a></li> <li><a href="https://www.askpython.com/python/python-functions" target="_blank">Python 函数</a></li> <li><a href="https://www.askpython.com/python/string/strings-in-python" target="_blank">Python 中的字符串</a></li> <li><a href="https://www.askpython.com/python/list/python-list" target="_blank">Python 列表</a></li> <li><a href="https://www.askpython.com/python/dictionary/python-dictionary-dict-tutorial" target="_blank">Python 字典</a></li> </ul> <h1 id="使用-python-进行分层聚类">使用 Python 进行分层聚类</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/hierarchical-clustering" target="_blank">https://www.askpython.com/python/examples/hierarchical-clustering</a></p> </blockquote> <p>聚类是一种将相似数据点分组在一起的技术,所形成的相似数据点组被称为聚类。</p> <p>很多时候,我们的数据没有任何标签;由于这一点,从中得出洞见和模式变得非常困难。</p> <p>在这种情况下,无监督聚类技术开始发挥作用。在层次聚类中,我们基本上构建了一个聚类的层次结构。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a3f86bdf7b64f2b55cc1bd5c3f9d5da5.png" alt="What Clustering Looks Like" loading="lazy"></p> <p><strong>What Clustering Looks Like</strong></p> <h2 id="层次聚类的类型"><strong>层次聚类的类型</strong></h2> <p><strong>层次聚类分为两种</strong>:</p> <ul> <li>凝聚层次聚类。</li> <li>分裂层次聚类</li> </ul> <h3 id="1凝聚层次聚类">1.<strong>凝聚层次聚类</strong></h3> <p>在<strong>凝聚层次聚类中,</strong>每个数据点被认为是单个聚类,使得聚类的总数等于数据点的数量。然后,我们继续根据相似性指标对数据进行分组,随着我们在层次结构中的向上移动,形成聚类。这种方法也称为自底向上方法。</p> <h3 id="2分裂式层次聚类">2.<strong>分裂式层次聚类</strong></h3> <p>分裂的层次聚类与凝聚的 HC 相反。这里,我们从包含所有数据点的单个集群开始。在每次迭代中,我们会根据距离度量将距离较远的点分开,直到每个聚类都有一个数据点。</p> <h2 id="执行分层聚类的步骤">执行分层聚类的步骤</h2> <p>让我们用一个例子来形象化地展示层次聚类是如何工作的。</p> <p>假设我们有与 4 名学生在数学和科学上的分数相关的数据,我们需要创建学生集群来获得洞察力。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/655ef1781c14814d4e291d0613654338.png" alt="Example Dataset" loading="lazy"></p> <p><strong>Example Dataset</strong></p> <p>现在我们有了数据,我们需要做的第一步是查看每个数据点之间的距离。</p> <p>为此,我们构建一个<a href="https://en.wikipedia.org/wiki/Distance_matrix" target="_blank">距离矩阵</a>。每个点之间的距离可以使用各种度量来找到,即欧几里德距离、曼哈顿距离等。</p> <p>在本例中,我们将使用欧几里德距离:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ce44259a4c6024dbc167a1c90ef48c50.png" alt="Euclidean Distance" loading="lazy"></p> <p><strong>Euclidean Distance</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f0ac63f3e26fd4eadbd6f3fc98c6bfd4.png" alt="Distance Calculated Between Each Data Point" loading="lazy"></p> <p><strong>Distance Calculated Between Each Data Point</strong></p> <p>我们现在在 S1 和 S2 之间形成了一个集群,因为它们彼此更接近。现在出现了一个问题,我们的数据现在是什么样子的?</p> <p>我们取了 S1 和 S2 得分的平均值,我们得到的值将代表该组的得分。我们可以考虑聚类中数据点的最大值或最小值,而不是平均值。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/41708fb13084589f6abb1c16468afe6a.png" alt="Dataset After First Clustering" loading="lazy"></p> <p><strong>Dataset After First Clustering</strong></p> <p>再次找到最近的点,并创建另一个集群。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6240a760b95e67da4fca0559ed0f3480.png" alt="Clustering S3 And S4" loading="lazy"></p> <p><strong>Clustering S3 And S4</strong></p> <p>如果我们重复上面的步骤,继续进行聚类,直到只剩下一个包含所有聚类的聚类,我们会得到类似这样的结果:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fb56ef24b9706d87df60aa9a71edb5c8.png" alt="Dendrogram Of Our Example " loading="lazy"></p> <p><strong>Dendrogram Of Our Example</strong></p> <p>我们得到的图形就是我们所说的<a href="https://en.wikipedia.org/wiki/Dendrogram" target="_blank">树状图</a>。树状图是一个类似树的图表,说明了由相应的分析产生的聚类的排列。x 轴上的样本会自动排列,表示彼此距离较近的点。</p> <p>选择最佳的集群数量可能是一项棘手的任务。但是根据经验,我们寻找具有最长“分支”或“最长树状图距离”的集群。聚类的最佳数量也受到专家知识、上下文等的影响。</p> <p>有了足够的想法,让我们继续用 python 实现一个。</p> <h2 id="用-python-实现层次聚类"><strong>用 Python 实现层次聚类</strong></h2> <p>让我们深入一个例子来最好地展示分层集群</p> <p>我们将使用 Iris 数据集来执行聚类。你可以在这里获得更多关于虹膜数据集<a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html" target="_blank">的细节。</a></p> <h3 id="1绘制和创建集群">1.绘制和创建集群</h3> <p><code>sklearn.cluster</code>模块为我们提供了<code>AgglomerativeClustering</code>类来对数据集进行聚类。</p> <p>作为输入参数,它需要多个集群(<code>n_clusters</code>)、<code>affinity</code>,这些集群对应于在创建<a href="https://www.askpython.com/python/examples/plot-k-means-clusters-python" target="_blank">集群</a>、<code>linkage</code>、<em>链接{ "沃德"、"完整"、"平均"、"单一" }、默认= "沃德"</em>时要使用的距离度量的类型。</p> <p>链接标准决定了在给定的观察组之间使用哪个距离。</p> <p>你可以在这里了解更多<code>AgglomerativeClustering</code>班<a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html" target="_blank">。</a></p> <pre><code class="language-py">#Importing required libraries from sklearn.datasets import load_iris from sklearn.cluster import AgglomerativeClustering import numpy as np import matplotlib.pyplot as plt #Getting the data ready data = load_iris() df = data.data #Selecting certain features based on which clustering is done df = df[:,1:3] #Creating the model agg_clustering = AgglomerativeClustering(n_clusters = 3, affinity = 'euclidean', linkage = 'ward') #predicting the labels labels = agg_clustering.fit_predict(df) #Plotting the results plt.figure(figsize = (8,5)) plt.scatter(df[labels == 0 , 0] , df[labels == 0 , 1] , c = 'red') plt.scatter(df[labels == 1 , 0] , df[labels == 1 , 1] , c = 'blue') plt.scatter(df[labels == 2 , 0] , df[labels == 2 , 1] , c = 'green') plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5f795f747c324076722ade8e74c40502.png" alt="Output From The Code Above" loading="lazy"></p> <p><strong>Output From The Code Above</strong></p> <p>在上面的代码中,我们认为集群的数量是 3。</p> <p>这一点很明显,因为 iris 数据集只包含 3 个不同的类,但在现实生活中,我们对数据执行无监督聚类,因为我们没有关于每个数据点所属标签的信息。</p> <p>因此,找出集群的最佳数量取决于一些领域的专业知识。但是很少有方法可以找出我们将在以后的文章中讨论的最佳集群。</p> <h3 id="2绘制树状图">2.绘制树状图</h3> <p><code>scipy.cluster</code>模块包含我们将用来绘制树状图的 hierarchy 类。</p> <p>层次结构<a href="https://www.askpython.com/python/oops/python-classes-objects" target="_blank">类</a>包含<code>dendrogram</code>方法和<code>linkage</code>方法。</p> <p><code>linkage</code>方法将数据集和最小化距离的方法作为参数,即 ward,并返回一个链接矩阵,该矩阵在提供给<code>dendrogram</code>方法时创建拟合数据的树状图。</p> <p>我们用一个例子来看看上面的说法是什么意思。</p> <pre><code class="language-py">#Importing libraries from sklearn.datasets import load_iris from sklearn.cluster import AgglomerativeClustering import numpy as np import matplotlib.pyplot as plt from scipy.cluster.hierarchy import dendrogram , linkage #Getting the data ready data = load_iris() df = data.data #Selecting certain features based on which clustering is done df = df[:,1:3] #Linkage Matrix Z = linkage(df, method = 'ward') #plotting dendrogram dendro = dendrogram(Z) plt.title('Dendrogram') plt.ylabel('Euclidean distance') plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/d6c5ac684d4f575c857eec0fbfeafeac.png" alt="Dendrogram Of The Data" loading="lazy"></p> <p><strong>Dendrogram Of The Data</strong></p> <h2 id="结论-39">结论</h2> <p>在本文中,我们试图获得层次聚类真正是什么及其工作机制背后的一些基本直觉。我们也了解了如何用 Python 构建树状图并最终实现 HC。</p> <p>快乐学习!</p> <h1 id="python-中的爬山算法">Python 中的爬山算法</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/hill-climbing-algorithm-in-python" target="_blank">https://www.askpython.com/python/examples/hill-climbing-algorithm-in-python</a></p> </blockquote> <p>在本文中,让我们试着理解爬山算法。这是人工智能领域常用的启发式搜索技术。启发式技术是选择多个选项中的哪一个最能成功实现特定目标的标准。</p> <p><em><strong>也读作:<a href="https://www.askpython.com/python/examples/branch-and-bound-search" target="_blank">分支和绑定搜索用 Python 实现</a></strong> 和</em></p> <h2 id="什么是爬山算法">什么是爬山算法?</h2> <p>爬山来自于<a href="https://www.askpython.com/python/examples/depth-first-search-in-a-graph" target="_blank">深度优先搜索</a>中的质量测量(生成和测试策略的变体)。这是一种优化策略,是局部搜索家族的一部分。</p> <p>这是一个相当简单的实现策略,因为它是一个受欢迎的首选方案。有爬山是有效的例子,即使更复杂的算法可能产生更大的好处。</p> <blockquote> <p>爬山可以用很多方法解决问题,但是有些方法比其他方法更好。旅行推销员问题可以用爬山来解决。找到一个访问每个城市的解决方案是很简单的,但是这个解决方案与理想的解决方案相比可能是不合格的。</p> </blockquote> <p>如果有一种排列选项的技术,以便首先探索最有希望的节点,则可以提高搜索效率。爬山是以深度优先的顺序通过路径树进行的,但是选项是根据一些启发值(即从当前状态到目标状态的剩余成本的度量)排列的。</p> <p>例如,在旅行推销员问题中,两个城市之间的直线距离可以作为剩余距离的启发式度量。</p> <h2 id="要记住的属性">要记住的属性</h2> <ul> <li>局部搜索算法</li> <li>遵循贪婪的方法</li> <li>没有回溯。</li> </ul> <h2 id="爬山算法的类型">爬山算法的类型</h2> <p><em><strong>简单爬山:</strong></em> 最简单的爬山方法叫做简单爬山。目标是登上这座山的最高峰。在这里,攀登者的脚步和移动决定了他如何移动。如果他认为他的下一步会比上一步更好,或者如果他停留在同一位置,他会继续移动。这个搜索只是关注他之前和之后的行为。</p> <p><em><strong>最陡爬坡:</strong></em> 与简单的爬山搜索不同,它会比较所有后续节点,并选择最接近答案的一个。因为它集中在每个节点上,而不仅仅是一个,所以最陡爬山搜索可以与最佳优先搜索相媲美。</p> <p><em><strong>随机爬山:</strong></em> 随机爬山中节点并不都集中在一起。它随机选择一个节点,然后决定是扩大它还是寻找更好的节点。</p> <p><em><strong>随机重启爬山:</strong></em> 试错法是随机重启算法的基础。直到没有达到目标,它迭代地搜索节点,并在每个阶段选择最佳候选。成功往往取决于山峰的形状。如果没有很多山脊、高原或局部最大值,到达那里会更容易。</p> <h2 id="爬山的简单例子">爬山的简单例子</h2> <p>为了更好地理解这个概念,让我们尝试使用爬山算法来实现一个旅行推销员的问题。下面是对该问题的描述。</p> <p>寻找多个点和必须访问的地点之间的最短路径是被称为“旅行推销员问题”(TSP)的算法问题的目标。这里的输入是一个城市坐标的 2D 数组,输出是一个整数列表,按顺序表示城市的数量(从零开始)</p> <h2 id="用-python-实现爬山算法">用 Python 实现爬山算法</h2> <pre><code class="language-py">import random import numpy as np import networkx as nx #coordinate of the points/cities coordinate = np.array([[1,2], [30,21], [56,23], [8,18], [20,50], [3,4], [11,6], [6,7], [15,20], [10,9], [12,12]]) #adjacency matrix for a weighted graph based on the given coordinates def generate_matrix(coordinate): matrix = [] for i in range(len(coordinate)): for j in range(len(coordinate)) : p = np.linalg.norm(coordinate[i] - coordinate[j]) matrix.append(p) matrix = np.reshape(matrix, (len(coordinate),len(coordinate))) #print(matrix) return matrix #finds a random solution def solution(matrix): points = list(range(0, len(matrix))) solution = [] for i in range(0, len(matrix)): random_point = points[random.randint(0, len(points) - 1)] solution.append(random_point) points.remove(random_point) return solution #calculate the path based on the random solution def path_length(matrix, solution): cycle_length = 0 for i in range(0, len(solution)): cycle_length += matrix[solution[i]][solution[i - 1]] return cycle_length #generate neighbors of the random solution by swapping cities and returns the best neighbor def neighbors(matrix, solution): neighbors = [] for i in range(len(solution)): for j in range(i + 1, len(solution)): neighbor = solution.copy() neighbor[i] = solution[j] neighbor[j] = solution[i] neighbors.append(neighbor) #assume that the first neighbor in the list is the best neighbor best_neighbor = neighbors[0] best_path = path_length(matrix, best_neighbor) #check if there is a better neighbor for neighbor in neighbors: current_path = path_length(matrix, neighbor) if current_path < best_path: best_path = current_path best_neighbor = neighbor return best_neighbor, best_path def hill_climbing(coordinate): matrix = generate_matrix(coordinate) current_solution = solution(matrix) current_path = path_length(matrix, current_solution) neighbor = neighbors(matrix,current_solution)[0] best_neighbor, best_neighbor_path = neighbors(matrix, neighbor) while best_neighbor_path < current_path: current_solution = best_neighbor current_path = best_neighbor_path neighbor = neighbors(matrix, current_solution)[0] best_neighbor, best_neighbor_path = neighbors(matrix, neighbor) return current_path, current_solution final_solution = hill_climbing(coordinate) print("The solution is \n", final_solution[1]) </code></pre> <h4 id="输出-1"><strong>输出</strong></h4> <p>解决方法是</p> <p>[2, 4, 8, 3, 7, 5, 0, 6, 9, 10, 1]</p> <h2 id="爬山的问题">爬山的问题</h2> <p>爬山有几个问题。搜索过程可能会到达一个不是解决方案的位置,但从那里没有任何行动来改善这种情况。如果我们到达了当地的最大值、平台或山脊,就会发生这种情况。</p> <p><em><strong>局部最大值:</strong></em> 一个状态比它所有的邻居都好,但并不比远处的其他一些状态好,(前面可能有更好的解,这个解称为全局最大值。)从这种状态来看,所有的招式看起来都更差。在这种情况下,回溯到某个更早的状态,尝试从不同的方向寻找解决方案。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e1e61ec9c3d4e24fd9ff88ada8e8bdab.png" alt="Local Maximum" loading="lazy"></p> <p>Local Maximum</p> <p><em><strong>高原:</strong></em> 是搜索空间中所有相邻状态值相同的平坦区域。不可能确定最佳方向。在这种情况下,向某个方向进行一次大的跳跃,并尝试进入搜索空间的一个新部分。它也被称为平坦最大值。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/bd0e4a5ae6190b9b1ed693360e39a87d.png" alt="Plateau" loading="lazy"></p> <p>Plateau</p> <p><em><strong>山脊:</strong></em> 是搜索空间中高于周围区域,但在任何一个方向上不能被单次移动穿越的区域。它是一种特殊的局部极大值。在进行测试之前,应用两个或更多的规则,即同时向几个方向移动。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/9ba33c41da36d224d249cb3e5be61acf.png" alt="Ridge" loading="lazy"></p> <p>Ridge</p> <h3 id="摘要-1">摘要</h3> <p>本文深入解释了爬山算法的概念。我们了解了解决著名的旅行推销员问题的不同类型以及算法的实现。爬山算法广泛应用于数据科学和人工智能领域。</p> <h1 id="从基础到高级的-matplotlib-直方图">从基础到高级的 Matplotlib 直方图</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/matplotlib/histogram-basic-to-advanced" target="_blank">https://www.askpython.com/python-modules/matplotlib/histogram-basic-to-advanced</a></p> </blockquote> <p>在今天的日报上,我们经常看到直方图和饼图解释股票或金融或新冠肺炎数据。毫无疑问,直方图使我们的日常生活变得更加容易。它们帮助我们直观地看到数据,并了解数据。在今天的这篇文章中,我们将学习直方图(从基础到高级),以帮助您进行数据分析或机器学习项目。</p> <h2 id="什么是直方图">什么是直方图?</h2> <p>直方图是一种条形图,用于表示数字数据分布。在直方图中,X 轴代表仓范围,Y 轴给出频率。直方图创建一个区间,将整个范围的值分布到区间中,并计算落入每个区间的值的数量(频率)。matplotlib.pyplot.hist()函数帮助我们绘制直方图。</p> <h2 id="python-中的-matplotlib-库是什么">Python 中的 Matplotlib 库是什么?</h2> <p>Matplotlib 是 Python 中最常用的数据可视化库之一。对于简单的可视化和复杂的可视化,它都是一个很好的工具。</p> <p>让我们快速看一下 matplotlib 直方图函数的语法:</p> <pre><code class="language-py">matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False) </code></pre> <p>| <strong>参数</strong> | <strong>描述</strong> |<br> | x | 这表示数组形式的输入参数。 |<br> | 垃圾箱 | 这表示值的范围。它可以接受整数值和序列值。 |<br> | 范围 | 通过此参数,包括箱的下限和上限范围。 |<br> | 密度 | 这通常包含布尔值,并表示为密度=计数/(总和(计数)* np.diff(面元))。 |<br> | 砝码 | 此参数表示每个值的权重。 |<br> | 累积的 | 该参数表示每个容器的计数以及先前值的容器计数。 |<br> | 底部 | 这表示每个箱的基线位置。 |<br> | 主机类型 | 该参数用于表示要绘制的直方图的类型。例如:条形、条形堆叠、阶梯或阶梯填充。如果你没有提到任何东西,它会把酒吧作为默认。 |<br> | 排列 | 这将有助于您确定直方图的位置。例如左、右或中间。它将取中间值作为默认值。 |<br> | 方向 | 此参数帮助您决定是要水平还是垂直绘制直方图。它将默认为垂直。 |<br> | 宽度 | 此参数帮助您设置条形相对于料箱宽度的相对宽度。 |<br> | 颜色 | 此参数将帮助您设置序列的颜色。 |<br> | 标签 | 此命令将帮助您设置直方图的标签。 |<br> | 叠放在一起的 | 此参数采用布尔值(真或假)。如果您将它作为 False 传递,那么数据将以并排的方式排列(如果您将 histtype 作为一个条给出),或者如果它是一个步骤,则数据将排列在彼此之上。如果您将此参数作为 True 传递,数据将相互堆叠。<br> 该参数的默认值为假。 |</p> <h2 id="导入-matplotlib-和必要的库">导入 Matplotlib 和必要的库</h2> <p>在开始绘制直方图之前,我们将导入所有必要的库。让我们来看看如何安装 matplotlib 和必要的库。</p> <pre><code class="language-py">import matplotlib.pyplot as plt import numpy as np import pandas as pd </code></pre> <p>现在,让我们从最基本的开始,然后我们将移动到高级直方图。</p> <h2 id="基本分布直方图">基本分布直方图</h2> <p>为了创建基本分布的直方图,我们在这里使用了 random NumPy 函数。为了表示数据分布,我们还传递了平均值和标准偏差值。</p> <p>在直方图函数中,我们已经提供了值的总计数、箱的数量和补丁的数量。</p> <p>我们还传递了输入参数,如密度、面颜色和 alpha,以使直方图更具代表性。你可以试着改变箱子的大小和数量。我们将直方图类型作为条形传递到这里。</p> <p>xlim 和 ylim 分别用于设置 X 轴和 Y 轴的最小值和最大值。如果您不希望有网格线,您仍然可以将 plt.grid 函数作为 False 传递。</p> <pre><code class="language-py">import matplotlib.pyplot as plt import numpy as np import pandas as pd # Using numpy random function to generate random data np.random.seed(19685689) mu, sigma = 120, 30 x = mu + sigma * np.random.randn(10000) # passing the histogram function n, bins, patches = plt.hist(x, 70, histtype='bar', density=True, facecolor='yellow', alpha=0.80) plt.xlabel('Values') plt.ylabel('Probability Distribution') plt.title('Histogram showing Data Distribution') plt.xlim(50, 180) plt.ylim(0, 0.04) plt.grid(True) plt.show() </code></pre> <p>输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/0c81d24b210c018a81809db71051dc39.png" alt="Image" loading="lazy"></p> <h2 id="带颜色分布的直方图">带颜色分布的直方图</h2> <p>用颜色表示绘制直方图是一种很好的方法,可以直观显示数据范围内的不同值。我们将对这种类型的情节使用支线剧情功能。我们已经删除了轴棘和 x,y 刻度,使情节看起来更像样。我们还添加了填充和网格线。</p> <p>对于颜色表示,我们已经将直方图分成分数或块,然后为直方图的不同部分设置不同的颜色。</p> <pre><code class="language-py">#importing the packages for colors from matplotlib import colors from matplotlib.ticker import PercentFormatter # Forming the dataset with numpy random function np.random.seed(190345678) N_points = 100000 n_bins = 40 # Creating distribution x = np.random.randn(N_points) y = .10 ** x + np.random.randn(100000) + 25 legend = ['distribution'] # Passing subplot function fig, axs = plt.subplots(1, 1, figsize =(10, 7), tight_layout = True) # Removing axes spines for s in ['top', 'bottom', 'left', 'right']: axs.spines[s].set_visible(False) # Removing x, y ticks axs.xaxis.set_ticks_position('none') axs.yaxis.set_ticks_position('none') # Adding padding between axes and labels axs.xaxis.set_tick_params(pad = 7) axs.yaxis.set_tick_params(pad = 15) # Adding x, y gridlines axs.grid(b = True, color ='pink', linestyle ='-.', linewidth = 0.6, alpha = 0.6) # Passing histogram function N, bins, patches = axs.hist(x, bins = n_bins) # Setting the color fracs = ((N**(1 / 5)) / N.max()) norm = colors.Normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = plt.cm.viridis_r(norm(thisfrac)) thispatch.set_facecolor(color) # Adding extra features for making it more presentable plt.xlabel("X-axis") plt.ylabel("y-axis") plt.legend(legend) plt.title('Customizing your own histogram') plt.show() </code></pre> <p>输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/65496592d3f849f9cbfa20d592643412.png" alt="Image 1" loading="lazy"></p> <h2 id="带条形图的直方图">带条形图的直方图</h2> <p>这很容易做到。为此,我们刚刚使用 Numpy random 函数创建了随机数据,然后我们使用了 hist()函数,并将 histtype 参数作为一个条传递。您可以将参数更改为条形堆叠台阶或台阶井。</p> <pre><code class="language-py">np.random.seed(9**7) n_bins = 15 x = np.random.randn(10000, 5) colors = ['blue', 'pink', 'orange','green','red'] plt.hist(x, n_bins, density = True, histtype ='step', color = colors, label = colors) plt.legend(prop ={'size': 10}) plt.show() </code></pre> <p>输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7337655a941d0809d89c73985c7c15e2.png" alt="Image 2" loading="lazy"></p> <h2 id="kde-图和直方图">KDE 图和直方图</h2> <p>这是另一种用 KDE 绘制直方图的有趣方法。在这个例子中,我们将在子图函数的帮助下绘制 KDE(内核密度估计)和直方图。KDE 图有助于确定给定空间中数据的概率。因此,结合 KDE 图和直方图,我们可以表示数据的概率分布。为此,我们首先通过生成均值和标准差的随机值创建了一个数据框,并为 loc 参数分配了均值,为 scale 参数分配了标准差。</p> <pre><code class="language-py">np.random.seed(9**7) n_bins = 15 x = np.random.randn(10000, 5) colors = ['blue', 'pink', 'orange','green','red'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) plt.legend(prop ={'size': 10}) plt.show() </code></pre> <p>输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/d9ce5df2f4786f7e65ec90745474301e.png" alt="Image 3" loading="lazy"></p> <h2 id="多变量直方图">多变量直方图</h2> <p>在本例中,我们使用“拉面评级”数据集来绘制包含多个变量的直方图。我们给三种不同品牌的拉面分配了不同的变量。我们已经使用 hist()函数三次来创建三个不同品牌的拉面的直方图,并绘制三个不同品牌的拉面获得 5 星评级的概率。</p> <pre><code class="language-py">import pandas as pd df = pd.read_csv("C://Users//Intel//Documents//ramen-ratings.csv") df.head() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/403f2979b8a9fc01295cc97bbbcb07c6.png" alt="Screenshot 372" loading="lazy"></p> <pre><code class="language-py">x1 = df.loc[df.Style=='Bowl', 'Stars'] x2 = df.loc[df.Style=='Cup', 'Stars'] x3 = df.loc[df.Style=='Pack', 'Stars'] # Normalize kwargs = dict(alpha=0.5, bins=60, density=True, stacked=False) # Plotting the histogram plt.hist(x1,**kwargs,histtype='stepfilled',color='b',label='Bowl') plt.hist(x2,**kwargs,histtype='stepfilled',color='r',label='Cup') plt.hist(x3,**kwargs,histtype='stepfilled',color='y',label='Pack') plt.gca().set(title='Histogram of Probability of Ratings by Brand', ylabel='Probability') plt.xlim(2,5) plt.legend(); </code></pre> <p>输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a055e797b23ecfded4af133a4b7813e3.png" alt="Image 5" loading="lazy"></p> <h2 id="二维直方图">二维直方图</h2> <p>2D 直方图是可视化数据的另一种有趣方式。我们可以使用函数 plt.hist2d 绘制一个直方图,我们可以像前面一样定制绘图和 bin 大小。下面让我们来看一个非常简单的 2D 直方图的例子。</p> <pre><code class="language-py">import numpy as np import matplotlib.pyplot as plt import random # Generating random data n = 1000 x = np.random.standard_normal(1000) y = 5.0 * x + 3.0* np.random.standard_normal(1000) fig = plt.subplots(figsize =(10, 7)) # Plotting 2D Histogram plt.hist2d(x, y,bins=100) plt.title("2D Histogram") plt.show() </code></pre> <p>输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/93b8f309115db8af0d47ae40910a978a.png" alt="Image 6" loading="lazy"></p> <h2 id="结论-40">结论</h2> <p>总之,我们学习了绘制直方图和自定义直方图的五种不同方法,以及如何在数据集中创建包含多个变量的直方图。这些方法将对您在任何数据科学项目中可视化数据有很大帮助。</p> <h1 id="赌场如何从大数据方法中获益">赌场如何从大数据方法中获益</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/how-casinos-can-benefit-from-big-data" target="_blank">https://www.askpython.com/python/how-casinos-can-benefit-from-big-data</a></p> </blockquote> <p>为了找到创新和竞争优势的新关系和见解,大数据赌丨博解决方案为每一个新赌场提供了必要的工具,包括必要的方法和先进技术,可以在几秒钟内检测、存储、搜索甚至分析数据。</p> <p>大数据是指我们研究领域中的大数据分析。简而言之,它是具有大规模、快速移动速度和不同类型变量的数据资产的积累,这些因素合在一起需要一个用于决策和增强洞察力的创新平台。下面,我们将介绍赌场如何从大数据方法中获益:</p> <h2 id="利用收集的数据增强用户体验">利用收集的数据,增强用户体验</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c263572da9dd69a9c05355ee6caba6f8.png" alt="Data Collection" loading="lazy"></p> <p>随着技术的进步和大数据解决方案的出现,数字赌场游戏以及游戏类型经历了彻底的转变。在大数据分析的帮助下,锦标赛组织者可以预测赌场游戏的结果,并根据预期给出活动的结构。</p> <p>当然,这是一些加强经常玩家的大胜利。它还允许用户跟踪世界各地的所有重大事件。大型橄榄球比赛的策略开发由人工智能和大数据驱动的算法提供支持。行业专家表示,游戏分析有可能为年轻一代创造重大的职业机会。</p> <h2 id="土地更有益的营销活动">土地更有益的营销活动</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/dacbf90e546f46645612acb441e90bca.png" alt="Marketing Campaigns" loading="lazy"></p> <p>赌场运营商,尤其是那些为新西兰人运营最新赌场网站的运营商,掌握着大量客户数据,包括身份和财务信息。作为 KYC 进程的一部分,这些信息必须披露给赌场运营商。运营商维护自己的专有软件来访问和分析这些信息。</p> <p>他们形成了自己的客户信息数据库。他们可以通过这种方式优化他们的网站。因此,运营商在营销方面做出关键决策,并且在追踪客户活动方面节省资源。向目标受众推广业务就属于这一类。</p> <p>通过专门调整营销内容,每个访问者将能够找到他们正在寻找的内容。使用这些指南,一家公司可以根据客户的需求计算出回应并做出大大小小的改进。通过跟踪客户的活动,它可以很容易地告诉客户什么对他们有利,什么对他们不利。</p> <p>简而言之,通过更好的广告、促销和优惠,他们可以提高销售额。通过更好的互动,他们可以与客户建立更好的信任,从而提高客户终身价值。最后,随着满意的客户在社交媒体和朋友圈独立推广他们的产品,他们开始改善他们的品牌倡导者。</p> <h2 id="诊断和处理欺诈">诊断和处理欺诈</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/24a5bf357c615b54581002282e6fb586.png" alt="Fraud" loading="lazy"></p> <p>赌场经营者担心安全问题,因为它已经成为该行业的一个主要问题。保护网站免受欺诈活动是该行业的首要任务之一。以前跟踪欺诈案件很困难,但现在随着安全系统的改进和大数据技术的结合,这可以轻松而准确地完成。</p> <p>随着大数据的出现,赌场领域已经发生了转变,变得透明,无论从玩家还是运营商的角度来看都是如此。目前,像 NORA(没有明显的关系意识)这样值得称赞的安全系统作为反作弊安全系统在拉斯维加斯赌场中越来越受欢迎。通过使用大数据,可以定位并堵塞安全系统中的漏洞。</p> <h2 id="成本降低">成本降低</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/318bdf3d5334d483898b990755a18951.png" alt="Cost Reduction" loading="lazy"></p> <p>在存储大量数据方面,Tableau、Hadoop 和 Amazon Web Services 等大数据技术比其他方法要便宜得多。此外,这些技术可以用来确定更有效的商业方法。</p> <p>Quantzig 的 Jesse Maida 解释了大数据分析解决方案如何将失败成本降低 35%,这对任何企业来说都是一笔巨大的节省。因此,企业应该关注大数据收集给公司带来的积极<a href="https://signalscv.com/2021/03/what-profits-could-data-science-bring-to-casinos/" target="_blank">财务影响。</a></p> <h2 id="允许消耗尽可能少的时间">允许消耗尽可能少的时间</h2> <p>大数据增强了我们更快、更高效地移动的能力。在过去,收集和分析信息的目标是得出可用于在工作场所做出更明智、更及时决策的信息。</p> <p>尽管技术不断进步,但这一过程已经变得更容易、更准确、耗时更少。因此,公司可以保持竞争力。</p> <h2 id="结论-41">结论</h2> <p>由于其动态性质,赌场行业已经完全依赖于大数据技术,这从根本上改变了整个游戏行业。在这样的行业中,大数据有着巨大的影响,它只能帮助加快进步。</p> <h1 id="python-在-web-开发中是如何使用的">Python 在 Web 开发中是如何使用的?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/how-is-python-used-in-web-development" target="_blank">https://www.askpython.com/python/how-is-python-used-in-web-development</a></p> </blockquote> <p>Web 开发是复杂的,作为一名 web 开发人员,为了达到您的 web 开发目标,您有许多最佳语言的选择。您对编程语言的选择将在很大程度上取决于您希望最终应用程序如何响应,以及实现您的目标所需的编码必须有多复杂。例如,您可能会选择 JavaScript,它是许多 web 开发任务中最流行的语言之一。</p> <p>但是还有一系列其他选择,在本文中,我们将了解 Python 以及为什么您可能会考虑在下一个 web 开发任务中使用 Python。为了评估 Python 在 web 上的使用,我们首先需要考虑为什么以及如何在 web 开发中使用 Python。</p> <h2 id="为什么选择-python">为什么选择 Python?</h2> <p>Python 是一种面向对象的编程语言,专注于快速动作开发。因此,它成为许多创业公司和新兴组织寻求竞争优势的首选。许多开发人员说,Python 的许多优点使它不仅是 web 开发的一种自然语言,而且是一种适应性很强的语言,可以很容易地适应不断变化的技术和不断变化的互联网。</p> <p>Python 是由吉多·范·罗苏姆在 1991 年发明的,目的是强调可读性和简单性。因为 Python 因其可读性和简单性而易于学习,所以它是初级程序员最喜欢的选择,Tim Peters 著名的 Python 19 条格言最好地总结了它的哲学:</p> <ol> <li>漂亮总比难看好。</li> <li>显性比隐性好。</li> <li>简单比复杂好。</li> <li>复杂总比复杂好。</li> <li>扁平的比嵌套的好。</li> <li>疏比密好。</li> <li>可读性很重要。</li> <li>特例不足以特殊到打破规则。</li> <li>虽然实用性战胜了纯粹性。</li> <li>错误永远不会无声无息地过去。</li> <li>除非明确沉默。</li> <li>面对暧昧,拒绝猜测的诱惑。</li> <li>应该有一种——最好只有一种——显而易见的方法来做这件事。</li> <li>尽管这种方式一开始可能并不明显,除非你是荷兰人。</li> <li>现在总比没有好。</li> <li>虽然永远也不会比现在的<em>对</em>好。</li> <li>如果实现很难解释,这是一个坏主意。</li> <li>如果实现很容易解释,这可能是一个好主意。</li> <li>名称空间是一个非常棒的想法——让我们多做一些吧!</li> </ol> <p>因为有了这样的规则,Python 可以在大多数主流操作系统上流畅运行,包括 Windows、iOS 和 Linux。它们还使得 Python 可以轻松地用于函数式、命令式或面向对象的编码风格。这意味着 Python 是任何项目和任何编程风格的首选语言。这就是我们发现 Python 被广泛用于 web 开发的一个原因,从旅游到医疗保健,再到金融。</p> <h2 id="为什么使用-python-进行-web-开发">为什么使用 Python 进行 Web 开发?</h2> <p>从根本上说,Web 开发是一种创建、构建和维护网站的方式,包括前端(用户界面)和后端(管理端)。Python 最适合 web 开发的后端,并且经常与前端语言(如 JavaScript)结合使用来处理用户界面。大多数使用 Python 的开发人员选择它的原因是 Python 极其高效,并且可以很容易地适应广泛的开发需求。Python 可以处理从科学应用到图形密集型游戏的任何东西,这使它成为大多数类型工作的最佳选择。事实上,在过去十年的大部分时间里,Python 一直是顶级编程语言,比第二名的 Java 更受欢迎。</p> <p>Python 人气激增的另一个重要原因是价格。Python 可以免费使用和分发,因为它是一个开源产品。这意味着公司不必担心支付版税,或者如果他们的需求发生变化,他们将网络开发扩展到最初的参数之外,他们将会遇到法律麻烦。他们可以不受限制地自由开发嵌入 Python 的新产品和服务。因为如此多的其他公司和产品也在使用 Python,这使得协调和交互更加容易。</p> <h2 id="python-开发入门">Python 开发入门</h2> <p>如果您对在 web 开发中使用 Python 感兴趣,您可能想知道如何最好地开始。有许多方法可以开始学习 Python。许多人都是自学的,通过在线教程或反复试验来学习 Python。然而,其他人更喜欢一种更正式、更结构化的学习 Python 的方式,比如在学院或大学里上课。这对于正在攻读计算机科学、信息系统或相关领域学位的学生来说尤其常见。</p> <p>如果你在学院或大学,并且需要 <a href="https://assignmentcore.com/python-homework/" target="_blank">Python 作业帮助</a>,你可以选择向专家支付编码作业帮助。专家可以为您提供所需的帮助,并且能够为您完成编程作业,这样您就可以少关注日常的作业,而将更多精力放在掌握 Python 所需的学习和研究上。</p> <p>无论您选择如何学习 Python,您总能找到确保您的 web 开发项目成功所需的支持。</p> <h1 id="如何更新一个-python-字典">如何更新一个 Python 字典?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/dictionary/how-to-update-a-python-dictionary" target="_blank">https://www.askpython.com/python/dictionary/how-to-update-a-python-dictionary</a></p> </blockquote> <p>嘿,伙计们!在本文中,我们将揭示更新 Python 字典的过程。</p> <hr> <h2 id="更新-python-字典的步骤入门">更新 Python 字典的步骤入门</h2> <p><a href="https://www.askpython.com/python/dictionary/python-dictionary-dict-tutorial" target="_blank">Python Dictionary</a> 是一种数据结构,它将数据元素保存在一个<strong>键-值对</strong>中,并且基本上作为一个<strong>无序的元素集合</strong>。为了更新相关键的值,Python Dict 内置了一个方法— <code>dict.update() method</code>来更新 Python 字典。</p> <p>dict.update()方法用于更新与输入字典中的键相关联的值。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">input_dict.update(dict) </code></pre> <p>该函数不返回任何值,而是用新关联的键值更新同一个输入字典。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">dict = {"Python":100,"Java":150} up_dict = {"Python":500} print("Dictionary before updation:",dict) dict.update(up_dict) print("Dictionary after updation:",dict) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Dictionary before updation: {'Python': 100, 'Java': 150} Dictionary after updation: {'Python': 500, 'Java': 150} </code></pre> <hr> <h3 id="用-iterable-更新-python-字典">用 Iterable 更新 Python 字典</h3> <p>除了更新字典的键值之外,我们还可以使用来自其他可迭代对象的值来追加和更新 Python 字典。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">dict.update(iterable) </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">dict = {"Python":100,"Java":150} print("Dictionary before updation:",dict) dict.update(C = 35,Fortran = 40) print("Dictionary after updation:",dict) </code></pre> <p>在上面的例子中,我们已经用传递给 update()函数的值更新了输入 dict。因此,输入 dict 会被追加,并用传递给函数的值进行更新。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">Dictionary before updation: {'Python': 100, 'Java': 150} Dictionary after updation: {'Python': 100, 'Java': 150, 'C': 35, 'Fortran': 40} </code></pre> <hr> <h2 id="更新嵌套-python-字典">更新嵌套 Python 字典</h2> <p>嵌套字典是字典中的字典。Python 嵌套字典可以使用以下语法使用相应的键值进行更新:</p> <p><strong>语法:</strong></p> <pre><code class="language-py">dict[outer-key][inner-key]='new-value' </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">dict = { 'stud1_info':{'name':'Safa','Roll-num':25},'stud2_info':{'name':'Ayush','Roll-num':24}} print("Dictionary before updation:",dict) dict['stud2_info']['Roll-num']=78 dict['stud1_info']['name']='Riya' print("Dictionary after updation:",dict) </code></pre> <p>在上面的示例中,我们已经将内部键的值:“Roll-num”外部键的值:“stud2_info”更新为 78,并将内部键的值:“name”外部键的值:“stud1_info”更新为“Riya”。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">Dictionary before updation: {'stud1_info': {'name': 'Safa', 'Roll-num': 25}, 'stud2_info': {'name': 'Ayush', 'Roll-num': 24}} Dictionary after updation: {'stud1_info': {'name': 'Riya', 'Roll-num': 25}, 'stud2_info': {'name': 'Ayush', 'Roll-num': 78}} </code></pre> <hr> <h2 id="结论-42">结论</h2> <p>因此,在本文中,我们已经了解了更新 Python 字典和嵌套字典的值的方法。</p> <p>我强烈建议读者阅读 <a href="https://www.askpython.com/python/dictionary" target="_blank">Python 字典教程</a>以深入理解字典概念。</p> <hr> <h2 id="参考-6">参考</h2> <ul> <li>Python 字典— JournalDev</li> </ul> <h1 id="python-http-模块您需要知道的一切">Python HTTP 模块–您需要知道的一切!</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/http-module" target="_blank">https://www.askpython.com/python-modules/http-module</a></p> </blockquote> <p>读者朋友们,你们好!在本文中,我们将详细关注 <strong>Python HTTP 模块</strong>。所以,让我们开始吧!!🙂</p> <p><em><strong>推荐阅读:<a href="https://www.askpython.com/python/examples/relu-function" target="_blank">Python 中的 ReLU 函数</a></strong></em></p> <hr> <h2 id="简明概述python-http-模块">简明概述–Python HTTP 模块</h2> <p>Python 是一种多用途的编程语言,它帮助我们轻松地在不同层次上执行各种操作。python 模块提供了大量的模块和内置函数来执行经典和定制/用户定义的操作。</p> <p>当涉及到<a href="https://www.askpython.com/python/beautiful-soup-web-scraping" target="_blank">数据抓取</a>,或者通过 API 或 JSON 数据路径获取信息时,我们需要能够打开到 web URL 的连接,然后在其上执行响应操作的函数。</p> <p>Python 为我们提供了 HTTP 模块。借助 HTTP 模块,我们可以轻松处理 web URL 连接并执行各种操作,例如:</p> <ol> <li><strong>获取请求</strong></li> <li><strong>发布请求</strong></li> <li><strong>上传请求</strong></li> <li><strong>从响应头</strong>中获取头,等等</li> </ol> <p>我们将通过 HTTP 模块来看看上面提到的每一个函数。HTTP 模块通常与 urllib 模块一起处理最新的 HTTP 请求。</p> <p>让我们开始吧!!</p> <hr> <h2 id="1建立-http-连接">1.建立 HTTP 连接</h2> <p>在使用 web URL 执行任何请求操作之前,与 URL 建立连接非常重要。在 HTTP 模块中,HTTPConnection()函数使我们能够在特定的端口(最好是 80)上打开到 URL 的连接,并且有一个超时期限。</p> <p><strong>语法</strong>:</p> <pre><code class="language-py">http.client.HTTPConnection('URL', port, timeout=) </code></pre> <ul> <li>URL:用来建立连接的 web URL。</li> <li>port:需要建立连接的端口号。</li> <li>超时:连接中止的宽限期。</li> </ul> <p><strong>举例</strong>:</p> <pre><code class="language-py">import http.client request = http.client.HTTPConnection('www.google.com', 80, timeout=10) print(request) </code></pre> <p><strong>输出</strong>:</p> <pre><code class="language-py"><http.client.HTTPConnection object at 0x00000223BAD2DDD8> </code></pre> <hr> <h2 id="2python-http-get-请求">2.Python HTTP GET 请求</h2> <p>使用 HTTP 模块,我们可以对 web URL 执行 GET 请求,我们可以使用它从 web URL 获得响应。使用 GET response,我们建立一个与 web URL 的 give-away 连接,获取由 URL 提供的响应数据,并分配一个对象来表示它。</p> <p>此外,还可以使用 request()函数的<strong>原因</strong>和<strong>状态</strong>属性来验证响应数据。</p> <p><strong>语法</strong>:</p> <pre><code class="language-py">request("GET") </code></pre> <p><strong>举例</strong>:</p> <pre><code class="language-py">import http.client data = http.client.HTTPSConnection("www.askpython.com") data.request("GET", "/") response = data.getresponse() print(response.reason) print(response.status) data.close() </code></pre> <p><strong>输出</strong>:</p> <pre><code class="language-py">OK 200 </code></pre> <h2 id="3python-http-post--put-请求">3.Python HTTP Post & Put 请求</h2> <p>除了 HTTP GET 请求,我们还可以使用 POST 请求来注入数据,即将数据发送到 URL,然后使用 GET 请求从 URL 获得响应。</p> <p>此外,如果我们希望修改某些数据并将其添加到 URL/API 的 <a href="https://www.askpython.com/python/examples/serialize-deserialize-json" target="_blank">JSON 数据</a>中,我们可以使用 PUT 请求来完成。使用 PUT 请求,我们可以将数据添加到 URL 的现有 JSON 中,并使用 GET 请求检查它的连接。</p> <p><strong>语法</strong>–<strong>发布请求</strong>:</p> <pre><code class="language-py">request('POST', '/post', json_data, headers) </code></pre> <p><strong>语法–上传请求</strong>:</p> <pre><code class="language-py">request("PUT", "/put", json_data) </code></pre> <h2 id="4从响应中检索标题列表">4.从响应中检索标题列表</h2> <p>一旦您建立了与 web URL 的连接并请求 GET 响应,我们现在就可以使用 getheaders()函数从可用的响应中提取和检索标题数据。getheaders()函数表示来自 GET 响应的标题数据列表。</p> <p><strong>语法</strong>:</p> <pre><code class="language-py">request.getheaders() </code></pre> <p><strong>举例</strong>:</p> <pre><code class="language-py">import http.client data = http.client.HTTPSConnection("www.askpython.com") data.request("GET", "/") response = data.getresponse() header = response.getheaders() print(header) print(response.reason) print(response.status) data.close() </code></pre> <p><strong>输出—</strong></p> <pre><code class="language-py">[('Connection', 'Keep-Alive'), ('Content-Type', 'text/html; charset=UTF-8'), ('Link', '<https://www.askpython.com/wp-json/>; rel="https://api.w.org/"'), ('Link', '</wp-content/themes/astra/assets/css/minified/style.min.css>; rel=preload; as=style,</wp-content/themes/astra/assets/css/minified/menu-animation.min.css>; rel=preload; as=style,</wp-includes/css/dist/block-library/style.min.css>; rel=preload; as=style,</wp-content/plugins/wp-to-twitter/css/twitter-feed.css>; rel=preload; as=style,</wp-content/plugins/easy-table-of-contents/vendor/icomoon/style.min.css>; rel=preload; as=style,</wp-content/plugins/easy-table-of-contents/assets/css/screen.min.css>; rel=preload; as=style,</wp-content/themes/obsidian/style.css>; rel=preload; as=style'), ('Etag', '"294191-1623490484;;;"'), ('X-LiteSpeed-Cache', 'hit'), ('Transfer-Encoding', 'chunked'), ('Date', 'Sun, 13 Jun 2021 07:30:37 GMT'), ('Server', 'LiteSpeed')] OK 200 </code></pre> <hr> <hr> <h2 id="结论-43">结论</h2> <p>到此,我们就结束了这个话题。如果你遇到任何问题,欢迎在下面评论。</p> <p>更多与 Python 编程相关的帖子,请继续关注我们。</p> <p>在那之前,学习愉快!!🙂</p> <h1 id="在-python-中使用-id函数">在 Python 中使用 id()函数</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/id-function-in-python" target="_blank">https://www.askpython.com/python/id-function-in-python</a></p> </blockquote> <p>大家好!在今天的文章中,我们将看看 Python 中的 id()函数。</p> <p>id()函数返回任何 <a href="https://www.askpython.com/python/oops/python-classes-objects" target="_blank">Python 对象</a>的身份。这将返回不同对象的整数标识号。</p> <p>底层的 CPython 实现使用<code>id()</code>函数作为对象在内存中的地址。</p> <p>让我们用一些例子来更好地理解这一点。</p> <hr> <h2 id="python-中-id函数的基本语法">Python 中 id()函数的基本语法</h2> <p>这个函数接受任何 Python 对象——无论是整数、浮点、字符串、列表、类、函数、lambda 等等,并返回一个整数 id。</p> <pre><code class="language-py">val = id(object) </code></pre> <hr> <h2 id="在-python-中使用-id">在 Python 中使用 id()</h2> <p>对象的 id 对于 Python 缓存这些变量的值很有用。这种使用<code>id()</code>检索缓存值的机制让 Python 性能更好!</p> <p>这在多个变量引用同一个对象的情况下也很有帮助。</p> <pre><code class="language-py">a = 1233.45 b = a print(id(a)) print(id(b)) </code></pre> <p><strong>输出</strong></p> <pre><code class="language-py">2775655780976 2775655780976 </code></pre> <p>在这种情况下,Python 更容易跟踪被引用的对象,因此 a 的 id()将与 b 的 id 相同。</p> <p>现在让我们试着在一些简单的 Python 对象上使用它。</p> <pre><code class="language-py">print(id(103)) # Int print(id(104)) print(id(10.25)) # Float print(id('Hello from AskPython')) # String print(id([1, 2, 3])) # List print(id(lambda x: x * x)) # Lambda </code></pre> <p><strong>输出</strong></p> <pre><code class="language-py">1658621232 1658621264 2775655780976 2775665230232 2775665206344 2775656111776 </code></pre> <p>你可以观察到,对于整数 103 和 104,它们的 ID 号只有 32 的区别。这是有道理的!为什么?</p> <p>还记得我们提到过<code>id()</code>是指对象的地址吗?</p> <p>id(104)是整数 103 之后的下一个地址块。因为 Python 中的整数存储为 4 个字节,所以这代表 32 位,这正好是它们的 id 号之间的差异。</p> <p>因此 Python 将所有整数的列表存储在顺序块中,这些块的间距相等。有道理?</p> <p>现在,让我们在琴弦上测试它们:</p> <pre><code class="language-py"># strings s1 = 'ABC' s2 = 'ABC' print(id(s1)) print(id(s2)) </code></pre> <p><strong>输出</strong></p> <pre><code class="language-py">2775656418080 2775656418080 </code></pre> <p>正如您所观察到的,Python 确实缓存了字符串以节省内存!</p> <p>请记住,缓存只能在不可变的 Python 对象上工作,比如 integer、string 和 floats。<a href="https://www.askpython.com/python/tuple/python-tuple" target="_blank">元组</a>、<a href="https://www.askpython.com/python/list/concatenate-multiple-lists-in-python" target="_blank">列表</a>等都是可变对象,这里缓存不起作用!</p> <p>为了证明这一点,让我们检查具有相同元素的两个列表的 id:</p> <pre><code class="language-py">>>> l1 = [1, 2, 3, 4] >>> l2 = [1, 2, 3 ,4] >>> id(l1) 2775665206344 >>> id(l2) 2775665185224 </code></pre> <p>这里,由于列表是可变的,所以不涉及任何缓存。</p> <h2 id="在自定义对象上使用-id">在自定义对象上使用 id()</h2> <p>我们还可以在自定义对象上使用 id()函数。</p> <p>让我们举一个简单的例子:</p> <pre><code class="language-py">class Student(): def __init__(self, name, id): self.name = name self.id = id s = Student('Amit', 10) t = Student('Rahul', 20) print(id(s)) print(id(t)) </code></pre> <p><strong>输出</strong></p> <pre><code class="language-py">2775665179336 2775665179448 </code></pre> <p>这指的是存储对象的内存地址,这对于两个实例来说显然是不同的!</p> <hr> <h2 id="结论-44">结论</h2> <p>在本文中,我们学习了在 Python 中使用 id()函数。这表示 Python 对象的底层内存地址,这在缓存不可变对象时很有用。</p> <h2 id="参考-7">参考</h2> <ul> <li>关于 Python id()函数的 JournalDev 文章</li> </ul> <hr> <h1 id="使用-python-opencv-识别图像中的关键点">使用 Python OpenCV 识别图像中的关键点</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/identifying-keypoints-in-images-opencv" target="_blank">https://www.askpython.com/python/examples/identifying-keypoints-in-images-opencv</a></p> </blockquote> <p>嘿伙计们!在本教程中,我们将了解如何使用 Python 编程语言中的 OpenCV 库来识别图像中的关键点。</p> <p>OpenCV 关键点用于各种计算机视觉应用,包括人体姿势检测、人脸识别、手势检测等。</p> <hr> <h2 id="为什么有必要识别图像中的关键点">为什么有必要识别图像中的关键点?</h2> <p>在执行图像处理时,计算机应该能够识别给定图像中的可比质量,而不管它经历的变换和旋转。</p> <p>计算机还应该能够发现同类照片之间的相似之处。这可以通过观察给定图像中的重要点来实现。</p> <p>例如,人脸上的主要点是两个眼角、两个嘴角、下巴和鼻尖。</p> <p>基本的概念是,不管一张图片有多大的变化,计算机应该在新的图像中发现相同的重要特征。</p> <p>当照片更新时,计算机检查某个关键点周围的像素值并识别它。</p> <hr> <h2 id="代码实现">代码实现</h2> <p>所有计算机视觉应用的基本概念是关键点的确定。在这一节中,我们将在给定的图片上标出关键点。</p> <p>为此,我们将采用 ORB 算法。首先,我们将包括 <strong>cv2 库</strong>和 <strong>cv2 imshow()方法</strong>。</p> <pre><code class="language-py">from google.colab.patches import cv2_imshow import cv2 </code></pre> <p>现在我们将使用 <strong>imread()方法</strong>来读取图片。我们要利用的图像是彩色的。因此,我们将通过将标志值设置为零来将其更改为黑白。</p> <pre><code class="language-py">img = cv2.imread('sample.jpg',0) cv2_imshow(img) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/863ecc8ad028c4acff0d9e67a7690969.png" alt="Loaded Image Keypoints" loading="lazy"></p> <p>Loaded Image Keypoints</p> <p>我们现在将利用 <strong>cv2。ORB create()方法</strong>。我们将传递 200 作为期望的点数。</p> <pre><code class="language-py">orb = cv2.ORB_create(200) </code></pre> <p>现在我们将使用 <strong>orb.detectAndCompute()</strong> 来查找关键点并计算描述符。最后将图片作为参数传递。</p> <p>它返回两个值:<strong>要点和描述</strong>。</p> <p>我们将使用 <strong>drawKeypoints()</strong> 方法绘制所有的关键点。然后,图片、关键点和标志值将作为输入发送。</p> <pre><code class="language-py">keypoint, des = orb.detectAndCompute(img, None) img_final = cv2.drawKeypoints(img, keypoint, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) </code></pre> <p>最后,我们将使用 <strong>cv2_imshow</strong> 来绘制图片中的所有关键点()。</p> <pre><code class="language-py">cv2_imshow(img_final) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/49fa4d4cbd1d519a8f452803d0a22762.png" alt="Final Keypoints Image Output" loading="lazy"></p> <p>Final Keypoints Image Output</p> <hr> <h2 id="结论-45">结论</h2> <p>恭喜你!您刚刚学习了如何使用 Python 中的 OpenCV 库在图像中找到关键点。</p> <p>希望你喜欢它!😇</p> <p>喜欢这个教程吗?无论如何,我建议你看一下下面提到的教程:</p> <ol> <li><a href="https://www.askpython.com/python/visualizing-colors-in-images" target="_blank">使用直方图可视化图像中的颜色–Python OpenCV</a></li> <li><a href="https://www.askpython.com/python/examples/draw-shapes-using-opencv" target="_blank">使用 OpenCV 绘制形状——完整的操作指南</a></li> <li><a href="https://www.askpython.com/python/examples/opencv-credit-card-reader" target="_blank">使用 OpenCV 的 Python 信用卡读卡器</a></li> <li><a href="https://www.askpython.com/python-modules/opencv-filter2d" target="_blank">Python OpenCV filter2D()函数——完整指南</a></li> </ol> <p>感谢您抽出时间!希望你学到了新的东西!!😄</p> <hr> <h1 id="python-编程语言中的图像姿态检测">Python 编程语言中的图像姿态检测</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/image-pose-detection-mediapipe" target="_blank">https://www.askpython.com/python-modules/image-pose-detection-mediapipe</a></p> </blockquote> <p>在本教程中,我们将实现一个程序,这将有助于检测图像中的姿态,并将它们标记为图像上的地标。我们先来了解一下什么是姿态检测。</p> <p>姿态估计是一种计算机视觉方法,用于跟踪人或物体的运动。这通常通过为所提供的项目定位关键点来实现。我们将使用<code>mediapipe</code>库,这是一个跨平台的开源工具,用于创建多模型机器学习管道。它能够实现前沿模型,如人脸识别、多手跟踪、头发分割、对象检测和跟踪等。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a1c26864fa1d1b88e866ac902cbf922f.png" alt="Pose Detection Demo" loading="lazy"></p> <p>Pose Detection Demo</p> <h2 id="用-python-实现图像后期检测器">用 Python 实现图像后期检测器</h2> <p>让我们从将我们需要的所有必要的库导入程序开始。这些库包括 OpenCV、mediapipe 和 matplotlib 库。</p> <pre><code class="language-py">import cv2 import mediapipe as mp import matplotlib.pyplot as plt </code></pre> <p>第一步是初始化我们的姿态检测模型。使用<code>solutions.pose</code>函数对其进行初始化。</p> <p>接下来,我们将使用 Pose 方法<code>mp_pose.Pose</code>存储 pose_image。该函数将接受许多参数。这些参数定义了我们正在处理的图像,并且还设置了置信度得分。我们将为视频设置一个类似的 Pose 方法,并传递必要的参数值。</p> <p>最后,我们将使用<code>drawing_utils</code>函数在图像上绘制所有的姿态估计点。</p> <p><strong>看下面的代码。</strong></p> <pre><code class="language-py">mp_pose = mp.solutions.pose pose_image = mp_pose.Pose(static_image_mode=True, min_detection_confidence=0.5) pose_video = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.7, min_tracking_confidence=0.7) mp_drawing = mp.solutions.drawing_utils </code></pre> <p>下面显示的函数是主函数,它将在向函数输入一些参数后估计姿态。</p> <p>我们将从创建用户提供的原始图像的副本开始,只是为了有一个安全的备份。接下来,我们将把图像转换成 RGB 格式,以便于处理。</p> <p>下一步将在<code>process</code>功能的帮助下对 RGB 转换图像进行姿态检测。现在我们检查标志的有效性,并决定是否需要绘制线和标志点。</p> <pre><code class="language-py">def detectPose(image_pose, pose, draw=False, display=False): original_image = image_pose.copy() image_in_RGB = cv2.cvtColor(image_pose, cv2.COLOR_BGR2RGB) resultant = pose.process(image_in_RGB) if resultant.pose_landmarks and draw: mp_drawing.draw_landmarks(image=original_image, landmark_list=resultant.pose_landmarks, connections=mp_pose.POSE_CONNECTIONS, landmark_drawing_spec=mp_drawing.DrawingSpec(color=(255,255,255), thickness=2, circle_radius=2), connection_drawing_spec=mp_drawing.DrawingSpec(color=(49,125,237), thickness=2, circle_radius=2)) if display: plt.figure(figsize=[22,22]) plt.subplot(121);plt.imshow(image_pose[:,:,::-1]) plt.title("Input Image",size=14) plt.axis('off'); plt.subplot(122);plt.imshow(original_image[:,:,::-1]) plt.title("Pose detected Image",size=14) plt.axis('off'); else: return original_image, resultant </code></pre> <p>最后,我们将针对一些图像测试上面代码片段中的函数。其中一些的输出如下所示。</p> <h2 id="样本输出">样本输出</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e3d0133fd536a39cd0c648b42e5eea7e.png" alt="Pose Detection Output 1" loading="lazy"></p> <p>Pose Detection Output 1</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/4797af2a1ff31161cfb8ea98f77e8ad9.png" alt="Pose Detection Output 2" loading="lazy"></p> <p>Pose Detection Output 2</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/eeee434d77a8feb05ffd0f6bbbb20e79.png" alt="Pose Detection Output 3" loading="lazy"></p> <p>Pose Detection Output 3</p> <h2 id="结论-46">结论</h2> <p>你可以看到结果非常令人满意,我们可以肯定地说,Mediapipe 在检测图像中的姿势方面做得非常好。</p> <p>感谢您的阅读!</p> <h1 id="python-中的图像处理边缘检测调整大小腐蚀和膨胀">Python 中的图像处理–边缘检测、调整大小、腐蚀和膨胀</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/image-processing-in-python" target="_blank">https://www.askpython.com/python/examples/image-processing-in-python</a></p> </blockquote> <p>图像处理是计算机科学中一个发展迅速的领域。它在越来越多的未来技术中得到了应用。Python 中的图像处理也为计算机视觉和人工智能等更高级的领域提供了空间。</p> <p>它是您可以对图像执行的操作的集合。通常需要这些操作来将图像转换成更容易训练的格式。其中一些操作是转换为灰度、旋转、裁剪和边缘检测。</p> <p><strong>一个合适的定义可以给出为:</strong></p> <p><em><strong>图像处理</strong>涉及到对一幅图像执行一些操作,以得到一幅增强的图像或者从中提取一些有用的信息。</em></p> <p>我们将在本教程中探讨一些重要的图像处理操作。</p> <p>在本教程中,我们使用 <strong>OpenCV</strong> 来实现图像处理的任务。这是我们上一篇关于<a href="https://www.askpython.com/python-modules/read-images-in-python-opencv" target="_blank">用 Python</a> 读取图像的后续教程。</p> <p>因此,让我们从学习如何使用 OpenCV 将图像导入 python 开始。在此之前,我们需要在我们的系统上安装 OpenCV。</p> <h2 id="安装-python-的图像处理库opencv">安装 Python 的图像处理库——OpenCV</h2> <p>您可以使用下面给出的 pip 命令安装 OpenCV:</p> <pre><code class="language-py">pip install opencv-python </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/18e58cb8d5811e3e29b05afe5bb0b608.png" alt="Install Opencv" loading="lazy"></p> <p>Install Opencv</p> <p>完成安装后,您可以在导入后开始使用它。</p> <p>将 OpenCV 导入 python 笔记本的代码行是:</p> <pre><code class="language-py">import cv2 </code></pre> <h2 id="使用-python-进行边缘检测">使用 Python 进行边缘检测</h2> <p>OpenCV 还为您提供了检测图像边缘的选项。边缘检测广泛应用于特征描述、图像分割、图像增强、图像恢复、模式识别和图像压缩。</p> <p>我们将使用 <strong>canny 边缘检测器</strong>执行边缘检测。Canny 边缘检测需要一个<strong>最大值</strong>和一个<strong>最小值</strong>来进行边缘检测。</p> <p>强度梯度大于 maxVal 的任何边缘肯定是边缘,而小于 minVal 的边缘肯定是非边缘,因此被丢弃。</p> <p>要执行边缘检测,请使用以下代码行:</p> <pre><code class="language-py">edges = cv2.Canny(image,50,300) </code></pre> <p>第一个参数是图像的变量名。</p> <p>保存结果图像的完整代码是:</p> <pre><code class="language-py">import cv2 image = cv2.imread("sample.jpg") edges = cv2.Canny(image,50,300) cv2.imwrite('sample_edges.jpg',edges) </code></pre> <p>生成的图像如下所示:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3b1b4fbf2f1a87111bc68e84ec553846.png" alt="Edge Detection" loading="lazy"></p> <p>Edge Detection</p> <h2 id="在-python-中调整图像大小">在 Python 中调整图像大小</h2> <p>调整大小是处理图像时需要执行的另一个重要操作。</p> <p>OpenCV 为您提供了一种调整图像大小的方法。要调整图像的大小,请使用以下代码行:</p> <pre><code class="language-py">res = cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC) </code></pre> <p>这里 <strong>fx</strong> 是沿水平轴的比例因子,而 <strong>fy</strong> 是沿垂直轴的比例因子。</p> <p>不同的插值方法可用于不同的功能。</p> <p>可以用 <strong>cv2。用于收缩的 INTER_AREA</strong> 和 <strong>cv2。INTER_CUBIC</strong> & <strong>cv2。INTER_LINEAR</strong> 用于变焦。与线性插值相比,三次插值速度较慢。</p> <h2 id="形态学图像处理操作">形态学图像处理操作</h2> <p>OpenCV 还为您提供了对图像执行形态学操作的选项,如腐蚀、膨胀、打开、关闭。</p> <p>形态学运算是基于形状的。要对图像应用形态学操作,您需要一个结构化元素。结构化元素是 2D 二进制矩阵。</p> <h3 id="1图像腐蚀">1.图像腐蚀</h3> <p>图像处理中侵蚀的基本概念类似于土壤侵蚀。它侵蚀了前景对象的边界。</p> <p>侵蚀会减少图像中的白色区域。</p> <p>要在图像上应用腐蚀,请使用下面几行代码。</p> <pre><code class="language-py">kernel = np.ones((5,5),np.uint8) erosion = cv2.erode(image,kernel,iterations = 30) </code></pre> <p>这里的第一行声明了内核,第二行使用内核来执行侵蚀。</p> <p><strong>保存结果图像的完整代码是:</strong></p> <pre><code class="language-py">import cv2 import numpy as np image = cv2.imread("sample.jpg") kernel = np.ones((5,5),np.uint8) erosion = cv2.erode(image,kernel,iterations = 30) cv2.imwrite('sample_erode.jpg',erosion) </code></pre> <p>生成的图像如下所示:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/898898229c76ea5c78e5a15d7f92d148.png" alt="Erosion" loading="lazy"></p> <p>Erosion</p> <h3 id="2图像膨胀">2.图像膨胀</h3> <p>膨胀是侵蚀的反义词。它增加了图像中的白色区域。</p> <p>要在图像上应用膨胀,请使用以下代码行:</p> <pre><code class="language-py">kernel = np.ones((5,5),np.uint8) dilation = cv2.dilate(image,kernel,iterations = 30) </code></pre> <p><strong>保存结果图像的完整代码如下:</strong></p> <pre><code class="language-py">import cv2 import numpy as np image = cv2.imread("sample.jpg") kernel = np.ones((5,5),np.uint8) dilation = cv2.dilate(image,kernel,iterations = 30) cv2.imwrite('sample_dilate.jpg',dilation) </code></pre> <p>生成的图像如下所示:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5d4f3200363f270f829eb3233ca3032b.png" alt="Dilation" loading="lazy"></p> <p>Dilation</p> <p>为了去除图像中的噪声,您可以先进行<strong>腐蚀,然后再进行膨胀。</strong></p> <h2 id="结论-47">结论</h2> <p>本教程是关于 python 中的图像处理的。我们讨论了 OpenCV 提供的一些基本的图像处理操作。想了解更多关于 OpenCV 的内容,可以参考他们的<a href="https://opencv-python-tutroals.readthedocs.io/en/latest/index.html" target="_blank">官方教程</a>。</p> <h1 id="python图像分割">Python:图像分割</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/image-segmentation" target="_blank">https://www.askpython.com/python/examples/image-segmentation</a></p> </blockquote> <p>你好,各位程序员!今天在本教程中,我们将了解什么是图像分割,并在后面的章节中使用 Python 编程语言中的 OpenCV 实现相同的功能。</p> <h2 id="什么是图像分割">什么是图像分割?</h2> <p>图像分割意味着将一组相似的像素和图像的部分组合在一起,以便于对图像中的对象进行分类和归类。</p> <h2 id="为什么需要图像分割">为什么需要图像分割?</h2> <p>图像分割是图像处理系统中的一个重要阶段,因为它有助于提取我们感兴趣的对象,并使未来的建模变得容易。它有助于将所需的对象与不必要的对象分开。</p> <h2 id="图像分割的应用">图像分割的应用</h2> <p>图像分割在现实生活中有着广泛的应用。其中一些如下:</p> <ol> <li>交通管理系统</li> <li>癌症和其他医学问题检测</li> <li>卫星图像分析</li> </ol> <h2 id="图像分割实现">图像分割实现</h2> <h3 id="1导入模块">1.导入模块</h3> <p>图像分割实现和图像绘制所需的所有必要模块都被导入到程序中。</p> <pre><code class="language-py">import numpy as np import cv2 from matplotlib import pyplot as plt </code></pre> <h3 id="2正在加载原始图像">2.正在加载原始图像</h3> <p>下一步是使用下面的代码加载原始图像(存储在与代码文件相同的目录中)。输出也显示在代码的正下方。</p> <pre><code class="language-py">img = cv2.imread('image1.jpg') img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) plt.figure(figsize=(8,8)) plt.imshow(img,cmap="gray") plt.axis('off') plt.title("Original Image") plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/2bfbc24b73da779fa071b95e5611e9f7.png" alt="Original Image Segmentation" loading="lazy"></p> <p>Original Img Segmentation</p> <h3 id="3转换为灰度">3.转换为灰度</h3> <p>为了使未来的图像处理不那么复杂和简单,我们将使用下面提到的代码将上一步加载的图像转换为灰度图像。输出图像也显示在代码下方。</p> <pre><code class="language-py">gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) plt.figure(figsize=(8,8)) plt.imshow(gray,cmap="gray") plt.axis('off') plt.title("GrayScale Image") plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/b26c1899a1db505e125ae8ccbc5a0de2.png" alt="Grayscale Image Segmentation" loading="lazy"></p> <p>Grayscale Img Segmentation</p> <h3 id="4转换为二进制反转图像">4.转换为二进制反转图像</h3> <p>为了更详细地研究图像,并对图像进行非常精确的研究,我们将使用下面提到的代码将图像转换为二进制反转图像。输出也与代码一起显示。</p> <pre><code class="language-py">ret, thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY_INV +cv2.THRESH_OTSU) plt.figure(figsize=(8,8)) plt.imshow(thresh,cmap="gray") plt.axis('off') plt.title("Threshold Image") plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/02d76afc49e84fcd7519ed427f53adef.png" alt="Threshold Img Segmentation" loading="lazy"></p> <p>Threshold Img Segmentation</p> <h3 id="5分割图像">5.分割图像</h3> <p>现在最后一步是在下面提到的代码的帮助下得到分割的图像。我们将在某处或其他地方使用所有以前的图像,以尽可能获得最准确的分割图像。</p> <pre><code class="language-py">kernel = np.ones((3, 3), np.uint8) closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE,kernel, iterations = 15) bg = cv2.dilate(closing, kernel, iterations = 1) dist_transform = cv2.distanceTransform(closing, cv2.DIST_L2, 0) ret, fg = cv2.threshold(dist_transform, 0.02*dist_transform.max(), 255, 0) cv2.imshow('image', fg) plt.figure(figsize=(8,8)) plt.imshow(fg,cmap="gray") plt.axis('off') plt.title("Segmented Image") plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8d015dd1efeaad175efaec54a23628fb.png" alt="Segmented Img Segmentation" loading="lazy"></p> <p>Segmented Img Segmentation</p> <h2 id="最终输出">最终输出</h2> <p>在所有的处理完成并且图像被分割之后,让我们借助于支线剧情在一帧中绘制所有的结果。下面提到了相同的代码。</p> <pre><code class="language-py">plt.figure(figsize=(10,10)) plt.subplot(2,2,1) plt.axis('off') plt.title("Original Image") plt.imshow(img,cmap="gray") plt.subplot(2,2,2) plt.imshow(gray,cmap="gray") plt.axis('off') plt.title("GrayScale Image") plt.subplot(2,2,3) plt.imshow(thresh,cmap="gray") plt.axis('off') plt.title("Threshold Image") plt.subplot(2,2,4) plt.imshow(fg,cmap="gray") plt.axis('off') plt.title("Segmented Image") plt.show() </code></pre> <p>最终结果如下。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cc474b153c7e329ee2d3e9c67eb65cc1.png" alt="Segmentation Output1" loading="lazy"></p> <p>Segmentation Output1</p> <p>对另一幅图像测试了相同的算法,结果如下。你可以看到结果相当令人满意。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/0c74aec917f6f93f4dfd067e3ebb28e0.png" alt="Segmentation Output2" loading="lazy"></p> <p>Segmentation Output2</p> <h2 id="结论-48">结论</h2> <p>今天我们学习了图像分割,现在你知道如何自己实现它了。自己尝试各种图像。编码快乐!</p> <p>感谢您的阅读!</p> <h1 id="python-中的图像阈值处理简单快速指南">Python 中的图像阈值处理——简单快速指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/image-thresholding" target="_blank">https://www.askpython.com/python/examples/image-thresholding</a></p> </blockquote> <p>嘿,程序员朋友!今天,我们将了解什么是图像阈值,以及如何在 python 编程语言中实现图像阈值。</p> <p>让我们直接进入概念!</p> <p><em><strong>也读作:</strong></em> <a href="https://www.askpython.com/python/examples/edge-detection-in-images" target="_blank"><em><strong>利用 Python 进行图像中的边缘检测</strong></em></a> 。</p> <h2 id="什么是图像阈值处理">什么是图像阈值处理?</h2> <p><code>Thresholding</code>定义为将图像分为两部分的过程,即:<strong>“前景”和“背景”</strong>。它主要用于各种图像处理任务,允许更好的图像识别和分割等。</p> <h2 id="不同类型的阈值技术">不同类型的阈值技术</h2> <p>人们可以实现各种阈值技术,这些技术在下面被命名和描述:</p> <p>| <strong>序列号</strong> | <strong>阈值技术名称</strong> | <strong>功能名称</strong> | <strong>描述</strong> |<br> | one | 二元阈值 | cv2。THRESH_BINARY | 1.(像素强度) >设置阈值:255(白色)<br> 2。否则设置为 0(黑色)。 |<br> | Two | 二元反向阈值 | cv2。阈值 _ 二进制 _INV | cv2 的反例。THRESH_BINARY。 |<br> | three | 零阈值 | cv2.THRESH_TOZERO | 1.(像素强度)< set threshold value : 0 (black)<br> 2。否则将其设置为白色 |<br> | four | 零反转阈值 | S7-1200 可编程控制器 | cv2 的反例。阈值为零 |<br> | five | 截断阈值 | cv2。TRUNC 阈值 | 1.(像素强度) >阈值:截断到阈值。<br> 2。像素值被设置为与阈值相同。<br> 3。所有其他值保持不变。 |</p> <p>Various Thresholding Techniques</p> <hr> <p><em><strong>也读: <a href="https://www.askpython.com/python/examples/images-to-pencil-sketch" target="_blank">Python:将图像转换成铅笔素描</a></strong></em></p> <h2 id="完整的代码-1">完整的代码</h2> <p>由于阈值方法具有用于实现的直接函数,我们可以直接查看阈值方法的代码实现。我希望你理解同样的编码实现。</p> <pre><code class="language-py">import cv2 import numpy as np img = cv2.imread('lori.jpg') img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret, thresh_hold = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY) ret, thresh_hold1 = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY_INV) ret, thresh_hold2 = cv2.threshold(img, 100, 255, cv2.THRESH_TOZERO) ret, thresh_hold3 = cv2.threshold(img, 100, 255, cv2.THRESH_TOZERO_INV) ret, thresh_hold4 = cv2.threshold(img, 100, 255, cv2.THRESH_TRUNC) thresh_hold = cv2.resize(thresh_hold, (960, 540)) cv2.imshow('Binary Threshold Image', thresh_hold) thresh_hold1 = cv2.resize(thresh_hold1, (960, 540)) cv2.imshow('Binary Threshold Inverted Image', thresh_hold1) thresh_hold2 = cv2.resize(thresh_hold2, (960, 540)) cv2.imshow('Threshold Tozero Image', thresh_hold2) thresh_hold3 = cv2.resize(thresh_hold3, (960, 540)) cv2.imshow('ThresholdTozero Inverted output', thresh_hold3) thresh_hold4= cv2.resize(thresh_hold4, (960, 540)) cv2.imshow('Truncated Threshold output', thresh_hold4) if cv2.waitKey(0) & 0xff == 25: cv2.destroyAllWindows() </code></pre> <hr> <h2 id="样本输出1">样本输出–1</h2> <h3 id="1原始图像输出">1.原始图像输出</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/57b0cc2a87f493d2a575dc6fc1595a6c.png" alt="Lori" loading="lazy"></p> <p>Lori</p> <h3 id="2二值阈值图像输出">2.二值阈值图像输出</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6a364f7bd97577a2ab06df5dae26cddf.png" alt="Binary Threshold Image" loading="lazy"></p> <p>Binary Threshold Image</p> <h3 id="3二进制反转阈值图像输出">3.二进制反转阈值图像输出</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ba6b27e43a821e64e19fbf66cb9a19f4.png" alt="Binary Inverted Threshold Image" loading="lazy"></p> <p>Binary Inverted Threshold Image</p> <h3 id="4阈值到零输出">4.阈值到零输出</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/15fa85fb07d593864e4e578947811909.png" alt="Threshold Tozero Image" loading="lazy"></p> <p>Threshold Tozero Image</p> <h3 id="5阈值归零反相输出">5.阈值归零反相输出</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ea78078aa6640ce6d7b05e20597ed975.png" alt="Threshold Tozero Inverted Image" loading="lazy"></p> <p>Threshold Tozero Inverted Image</p> <h3 id="6截断阈值图像输出">6.截断阈值图像输出</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/162d963d9d9e397d3a9b9f5ced54cbb8.png" alt="Truncated Threshold Image" loading="lazy"></p> <p>Truncated Threshold Image</p> <hr> <h2 id="样本输出2">样本输出–2</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3ed9cddc5fa6d88925bb5e834577cf9b.png" alt="Threshold Sample Output 2" loading="lazy"></p> <p>Threshold Sample Output 2</p> <hr> <h2 id="结论-49">结论</h2> <p>最后,我想让你自己尝试对不同的图像进行阈值处理,看看不同图像的输出结果。感谢您的阅读!</p> <p>快乐学习!</p> <h1 id="imageenchance增强-python-中的图像">ImageEnchance:增强 Python 中的图像</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/imageenchance" target="_blank">https://www.askpython.com/python-modules/imageenchance</a></p> </blockquote> <p>你好,程序员朋友!在本教程中,我们将讨论枕头库下 Python 中可用的<code>ImageEnchance</code>库。借助子库中的各种功能,它可以用于以多种方式处理图像。</p> <p><em><strong>也读作:<a href="https://www.askpython.com/python/visualizing-colors-in-images" target="_blank">使用直方图可视化图像中的颜色——Python OpenCV</a></strong></em></p> <p>我们开始吧!</p> <h2 id="图像增强color函数">图像增强。Color()函数</h2> <p>这个函数返回一个图像输出,但是颜色发生了变化。因子值可以是您想要的任何值。值 0 表示黑白图像,值 1 表示原始图像。</p> <p>让我们从显示原始图像开始。我已经采取了一个样本图像的玫瑰,你可以采取任何其他图像你想要的。</p> <pre><code class="language-py">from PIL import ImageEnhance, Image img = Image.open('samp.jpg') factor = 1.0 enhancer = ImageEnhance.Color(img) enhancer.enhance(factor).show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/41afeeffab88261104d1e73a498f6024.png" alt="ImageEnhancer Original Image" loading="lazy"></p> <p>ImageEnhancer Original Image</p> <p>现在,让我们试着想象同一张图片的黑白版本。</p> <pre><code class="language-py">from PIL import ImageEnhance, Image img = Image.open('samp.jpg') factor = 0.0 enhancer = ImageEnhance.Color(img) enhancer.enhance(factor).show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f2aaf2173dab9b508bf65f1275fc7473.png" alt="ImageEnhancer Black And White Image" loading="lazy"></p> <p>ImageEnhancer Black And White Image</p> <p>你想知道如果我给函数传递一个负值会发生什么吗?很明显,图像将开始向负方向移动。下面看看。</p> <pre><code class="language-py">from PIL import ImageEnhance, Image img = Image.open('samp.jpg') factor = -1.0 enhancer = ImageEnhance.Color(img) enhancer.enhance(factor).show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fa395f4e50f26a7edd663ce56cd6b836.png" alt="ImageEnhancer Negative Image" loading="lazy"></p> <p>ImageEnhancer Negative Image</p> <h2 id="图像增强亮度函数">图像增强。亮度()函数</h2> <p>你也可以使用下面的代码来调整图像的亮度。我们需要做的就是使用<code>ImageEnhance.Brightness</code>函数捕捉图像的当前亮度,然后对图像应用新的亮度因子。</p> <pre><code class="language-py">from PIL import ImageEnhance, Image img = Image.open('samp.jpg') curr_bri = ImageEnhance.Brightness(img) new_bri = 2.0 enhancer = curr_bri.enhance(new_bri) enhancer.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6f53d41ead3222899a53c7ef11909cf2.png" alt="ImageEnhancer Changed Brightness" loading="lazy"></p> <p>ImageEnhancer Changed Brightness</p> <h2 id="图像增强contrast函数">图像增强。Contrast()函数</h2> <p>当此处的因子值设置为 0.0 时,将给出纯灰图像,而值 1.0 将返回原始图像。我们将保持该值为 3,以查看高对比度图像。</p> <pre><code class="language-py">from PIL import ImageEnhance, Image img = Image.open('samp.jpg') factor = 3.0 enhancer = ImageEnhance.Contrast(img) enhancer.enhance(factor).show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1a2007c598b2d0191d67f97844408c02.png" alt="ImageEnhancer High Contrast Image" loading="lazy"></p> <p>ImageEnhancer High Contrast Image</p> <h2 id="图像增强锐度函数">图像增强。锐度()函数</h2> <p>在此功能的帮助下,您还可以体验一下图像的清晰度。这里的因子设置为 30,以获得更清晰的图像。值越低,图像越模糊!</p> <pre><code class="language-py">from PIL import ImageEnhance, Image img = Image.open('samp.jpg') factor = 30.0 enhancer = ImageEnhance.Sharpness(img) enhancer.enhance(factor).show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/228ee864f126bb0b271a7f0cfa44080c.png" alt="ImageEnhancer Sharpen Image" loading="lazy"></p> <p>ImageEnhancer Sharpen Image</p> <h2 id="结论-50">结论</h2> <p>我希望您在 Python 中使用 ImageEnchance 库时感到愉快。尝试所有不同的函数和不同的值,并惊讶于结果是多么完美!</p> <p>编码快乐!</p> <p><em><strong>也可阅读:<a href="https://www.askpython.com/python/examples/denoising-images-in-python" target="_blank">Python 中的图像去噪——分步指南</a></strong></em></p> <h1 id="枕头中的-imageops-模块简介">枕头中的 ImageOps 模块简介</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/imageops-module-in-pillow" target="_blank">https://www.askpython.com/python/examples/imageops-module-in-pillow</a></p> </blockquote> <p>程序员们,你们好!在本教程中,我们将看看 Python 的 ImageOps 模块。</p> <p>该模块包括许多预置的图像处理方法。此外,大多数操作者只处理 L 和 RGB 图像。ImageOps 模块的许多功能如下所列。</p> <hr> <h2 id="选择的原始图像">选择的原始图像</h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/583979f37caee396148e9165f3493ada.png" alt="ImageOps Original Image" loading="lazy"></p> <p>ImageOps Original Image</p> <hr> <h2 id="使用枕头的自动构建功能">使用枕头的自动构建功能</h2> <p>自动对比度功能用于均衡图片的对比度。它需要三个参数:image、cutoff 和 ignore。若要处理图像,请使用 image 参数。</p> <p>为了使图像对比度正常化,采用了截止值。ignore 参数用于隐藏背景像素。这个函数产生一个图片作为结果。</p> <pre><code class="language-py">from PIL import ImageOps, Image img = Image.open('pic1.jpg') img2 = ImageOps.autocontrast(img, cutoff=40) img2.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/229687235c801ad9b2b95ef7ec7e0a51.png" alt="ImageOps Autocontrast" loading="lazy"></p> <p>ImageOps Autocontrast</p> <hr> <h2 id="使用-python-pillow-的着色功能">使用 Python Pillow 的着色功能</h2> <p>用这个功能给灰度照片上色。它需要使用总共七个参数。第一个参数是要着色的图片。第二个选项是黑色,它只接受黑色像素作为输入。</p> <p>同样,第三个参数是 white,它接受白色像素作为输入。第四个选项 mid 用于中间色调输入像素。最后三个参数是黑点、白点和中间点。</p> <p>这三个参数各自的映射都有一个整数输入[0,255]。colorize 函数创建一个图像并返回它。</p> <pre><code class="language-py">from PIL import ImageOps, Image img = Image.open('pic1.jpg') img2 = ImageOps.colorize(img, black="red", white="white", mid="yellow") img2.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/778a35f3a6c792a929b4637b6e508b8c.png" alt="ImageOps Colorize" loading="lazy"></p> <p>ImageOps Colorize</p> <hr> <h2 id="使用-python-pillow-反转功能">使用 Python Pillow 反转功能</h2> <p>此功能用于通过反转图片来否定图片。例如,反转功能接受单个图片输入并产生反转图像。</p> <pre><code class="language-py">from PIL import ImageOps, Image img = Image.open('pic1.jpg') img2 = ImageOps.invert(img) img2.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/bff49269276d2647b47a00a9ec8a9811.png" alt="ImageOps Invert" loading="lazy"></p> <p>ImageOps Invert</p> <hr> <h2 id="极化函数">极化函数</h2> <p>该功能减少了每个颜色通道中的位数。它需要两个参数。第一个输入是图片,第二个参数是 bits,它记录每个通道中的位数。</p> <pre><code class="language-py">from PIL import ImageOps, Image img = Image.open('pic1.jpg') img2 = ImageOps.posterize(img, 3) img2.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/527051b74f3e55b093d5053df9df397a.png" alt="ImageOps Polorize" loading="lazy"></p> <p>ImageOps Polorize</p> <hr> <h2 id="结论-51">结论</h2> <p>恭喜你!您刚刚了解了枕头中的 ImageOps 模块。希望你喜欢它!😇</p> <p>喜欢这个教程吗?无论如何,我建议你看一下下面提到的教程:</p> <ol> <li><a href="https://www.askpython.com/python-modules/xlrd-module" target="_blank">xlrd 模块——如何在 Python 中处理 Excel 文件?</a></li> <li>Python Yagmail 模块——发送电子邮件的简单方法!</li> <li><a href="https://www.askpython.com/python-modules/pyzbar-module" target="_blank">pyzbar 模块:用 Python 解码条形码</a></li> </ol> <p>感谢您抽出时间!希望你学到了新的东西!!😄</p> <hr> <h1 id="使用-python-将图像转换成卡通">使用 Python 将图像转换成卡通</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/images-into-cartoons" target="_blank">https://www.askpython.com/python/examples/images-into-cartoons</a></p> </blockquote> <p>你好,读者!在本教程中,我们将学习如何把图像变成卡通!很酷吧?!所以让我们开始吧!</p> <h2 id="1导入模块-1">1.导入模块</h2> <p>每个程序的第一步是将所有必要的模块(如果有的话)导入到我们的文件中。对于这个问题,我们将导入三个模块,即 openCV,numpy 和 matplotlib 模块。</p> <pre><code class="language-py">import cv2 import numpy as np import matplotlib.pyplot as plt </code></pre> <h2 id="2加载并绘制原始图像">2.加载并绘制原始图像</h2> <p>下一步是使用<code>imread</code>功能读取图像,然后在<code>cvtColor</code>功能的帮助下将其转换为 RGB 格式。然后我们使用<code>imshow</code>函数绘制图像。相同的代码如下所示:</p> <pre><code class="language-py">img = cv2.imread("image.jpg") img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) plt.figure(figsize=(10,10)) plt.imshow(img) plt.axis("off") plt.title("Original Image") plt.show() </code></pre> <h2 id="3将图像转换为灰度">3.将图像转换为灰度</h2> <p>该过程的下一步是使用<code>cvtColor</code>功能将图像转换成灰度格式。这样做的原因是它简化了过程,并有助于降低程序的时间复杂度。</p> <p>实现相同功能的代码如下所示。</p> <pre><code class="language-py">gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 5) plt.figure(figsize=(10,10)) plt.imshow(gray,cmap="gray") plt.axis("off") plt.title("Grayscale Image") plt.show() </code></pre> <h2 id="4获取边缘图像">4.获取边缘图像</h2> <p>为了让事情变得简单,我们将获得灰度图像的边缘图像,然后将 T2 卷积网络应用于图像。</p> <p>通过使用<code>adaptiveThreshold</code>并设置所需的参数来获得边缘图像,也可以做到这一点。下面显示了相同的代码。</p> <pre><code class="language-py">edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) plt.figure(figsize=(10,10)) plt.imshow(edges,cmap="gray") plt.axis("off") plt.title("Edged Image") plt.show() </code></pre> <h2 id="5把图像变成卡通">5.把图像变成卡通</h2> <p>最后一步是使用<code>bilateralFilter</code>函数应用卷积滤波器。然后,我们利用<a href="https://www.askpython.com/python-modules/numpy/numpy-bitwise-operations" target="_blank">位运算</a>,传递原始图像和边缘图像,将图像变成卡通。</p> <p>相同的代码如下所示。</p> <pre><code class="language-py">color = cv2.bilateralFilter(img, 9, 250, 250) cartoon = cv2.bitwise_and(color, color, mask=edges) plt.figure(figsize=(10,10)) plt.imshow(cartoon,cmap="gray") plt.axis("off") plt.title("Cartoon Image") plt.show() </code></pre> <h2 id="把图像变成卡通的最终输出">把图像变成卡通的最终输出</h2> <p>下图显示了从原始图像到卡通图像的所有不同版本的图像。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/60e39d8e5c196aeb5185749271a93df0.png" alt="Cartoonify Image Output Images into Cartoons" loading="lazy"></p> <p>Cartoonify Image Output</p> <p>代码已针对另一个图像进行了测试。结果如下。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a0052201bd689a5f32f67a48ecaea18c.png" alt="Cartoonify Image Output 2 Images into Cartoons" loading="lazy"></p> <p>Cartoonify Image Output 2</p> <h2 id="结论-52">结论</h2> <p>恭喜你!今天你学会了如何通过几行代码把图片变成卡通。</p> <p>希望你学到了一些东西!感谢您的阅读!</p> <h1 id="python将图像转换为铅笔草图">Python:将图像转换为铅笔草图</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/images-to-pencil-sketch" target="_blank">https://www.askpython.com/python/examples/images-to-pencil-sketch</a></p> </blockquote> <p>你好。今天我们将学习如何在 OpenCV 的帮助下将图像转换为铅笔草图,并使用 <a href="https://www.askpython.com/python-modules/matplotlib/python-matplotlib" target="_blank">matplotlib</a> 在不同阶段绘制图像。</p> <p><em><strong>推荐阅读:<a href="https://www.askpython.com/python/examples/edge-detection-in-images" target="_blank">Python 中的边缘检测</a></strong></em></p> <h2 id="1导入模块-2">1.导入模块</h2> <p>让我们首先从将模块导入我们的程序开始。我们将利用 OpenCV 函数和 matplotlib 模块来绘制图像。</p> <p>我们也将根据我的喜好设置绘图风格。</p> <pre><code class="language-py">import cv2 import matplotlib.pyplot as plt plt.style.use('seaborn') </code></pre> <h2 id="2加载和绘制原始图像">2.加载和绘制原始图像</h2> <p>现在我们将通过使用获取文件路径的<code>imread</code>函数将图像文件加载到我们的程序中。请确保文件路径正确。</p> <p>我们还将改变图像的颜色代码为 RGB 格式,以获得原始颜色,并使用<code>imshow</code>函数绘制图像。</p> <p>相同的代码如下所示。</p> <pre><code class="language-py">img = cv2.imread("image1.png") img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) plt.figure(figsize=(8,8)) plt.imshow(img) plt.axis("off") plt.title("Original Image") plt.show() </code></pre> <p>我一直使用的图像是在上述代码的帮助下绘制的,如下所示。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/03cd1e9c080043220bea1f75afd340a3.png" alt="Original Image Pencil Sketch" loading="lazy"></p> <p>Original Image Pencil Sketch</p> <h2 id="3将图像转换为灰度-1">3.将图像转换为灰度</h2> <p>为了降低图像的复杂性并使处理更容易,我们将借助<code>cvtColor</code>功能将图像转换为灰度图像。下面提到的代码帮助绘制了相同的图形。</p> <pre><code class="language-py">img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) plt.figure(figsize=(8,8)) plt.imshow(img_gray,cmap="gray") plt.axis("off") plt.title("GrayScale Image") plt.show() </code></pre> <p>输出图像如下所示。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/af90e8179ef3c76be45988215c96902f.png" alt="GrayScale Image Pencil Sketch" loading="lazy"></p> <p>GrayScale Image Pencil Sketch</p> <h2 id="4反转图像">4.反转图像</h2> <p>现在下一步是反转图像。现在你的问题是为什么要这么做?同样的答案是,当图像被倒置时,它有助于更精确和详细地研究图像。</p> <p>更详细的研究对于草图生成是重要的,因为草图需要精确和良好。下面显示了反转图像的代码。</p> <pre><code class="language-py">img_invert = cv2.bitwise_not(img_gray) plt.figure(figsize=(8,8)) plt.imshow(img_invert,cmap="gray") plt.axis("off") plt.title("Inverted Image") plt.show() </code></pre> <p>反转图像的输出如下所示。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a0c25288de88a9ec932784fe1a056897.png" alt="Inverted Image Pencil Sketch" loading="lazy"></p> <p>Inverted Image Pencil Sketch</p> <p>除此之外,我们还将平滑图像,以确保我们获得的草图不那么尖锐和平滑。相同的代码如下所示。</p> <pre><code class="language-py">img_smoothing = cv2.GaussianBlur(img_invert, (21, 21),sigmaX=0, sigmaY=0) plt.figure(figsize=(8,8)) plt.imshow(img_smoothing,cmap="gray") plt.axis("off") plt.title("Smoothen Image") plt.show() </code></pre> <p>输出图像如下所示。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1775d416d6b77be2e137480d0814209a.png" alt="Smooth Inverted Image Pencil Sketch" loading="lazy"></p> <p>Smooth Inverted Image Pencil Sketch</p> <h2 id="5将您的图像转换为铅笔草图">5.将您的图像转换为铅笔草图</h2> <p>现在,整个图像处理已经完成,我们将把先前的输出传递给函数,并传递正确和准确的参数,以便对图像进行适当的更改。下面的代码中也提到了这一点。</p> <pre><code class="language-py">final = cv2.divide(img_gray, 255 - img_smoothing, scale=255) plt.figure(figsize=(8,8)) plt.imshow(final,cmap="gray") plt.axis("off") plt.title("Final Sketch Image") plt.show() </code></pre> <p>最终输出如下所示。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1276ded9afc13b885da0bb5749673c5d.png" alt="Final Sketch Pencil Sketch images to pencil sketches" loading="lazy"></p> <p>Final Sketch Pencil Sketch</p> <h2 id="6最终输出">6.最终输出</h2> <p>下面的代码将使用支线剧情显示一帧中的所有图像。</p> <pre><code class="language-py">plt.figure(figsize=(20,20)) plt.subplot(1,5,1) plt.imshow(img) plt.axis("off") plt.title("Original Image") plt.subplot(1,5,2) plt.imshow(img_gray,cmap="gray") plt.axis("off") plt.title("GrayScale Image") plt.subplot(1,5,3) plt.imshow(img_invert,cmap="gray") plt.axis("off") plt.title("Inverted Image") plt.subplot(1,5,4) plt.imshow(img_smoothing,cmap="gray") plt.axis("off") plt.title("Smoothen Image") plt.subplot(1,5,5) plt.imshow(final,cmap="gray") plt.axis("off") plt.title("Final Sketch Image") plt.show() </code></pre> <p>输出显示如下。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/bfc090dbaf21942de7938ab8f4421b1e.png" alt="All Outputs Pencil Sketch Output images to pencil sketches" loading="lazy"></p> <p>All Outputs Pencil Sketch Output</p> <p>你可以看到结果相当准确!厉害!同样的代码被用于另一个图像,结果非常好!看一看一样的。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/0aedabafae3b1dadc75771fdda9af737.png" alt="All Outputs Pencil Sketch Output 1 images to pencil sketches" loading="lazy"></p> <p>All Outputs Pencil Sketch Output 1</p> <h2 id="结论-53">结论</h2> <p>所以今天我们学习了如何把我们的图像变成铅笔素描。干得好!自己尝试一些图片。</p> <p>编码快乐!敬请关注更多此类教程!</p> <h1 id="python-中的不可变是什么意思">Python 中的“不可变”是什么意思?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/oops/immutable-objects-in-python" target="_blank">https://www.askpython.com/python/oops/immutable-objects-in-python</a></p> </blockquote> <p>在 Python 中每个实体都是一个<a href="https://www.askpython.com/python/oops/python-classes-objects" target="_blank">对象</a>的情况下,不可变是什么意思?与其他一些编程语言不同,Python 不需要显式指定赋给变量的数据类型。相反,它会根据您提供的值自动分配<a href="https://www.askpython.com/python/python-data-types" target="_blank">数据类型</a>。</p> <p>简而言之,每个变量保存一个对象实例,并被赋予一个惟一的对象 ID,该 ID 是在程序运行时创建的。对象 ID 是一个整数,表示存储变量值的<a href="https://www.askpython.com/python-modules/garbage-collection-in-python" target="_blank">内存位置</a>。</p> <p>要获得每个对象的 id,需要打开 Python Shell,调用默认的 ID()函数,并传递变量名。这里有一个例子:</p> <pre><code class="language-py">#Initializing the variable a = "this is not a random string" #We call the id() function with the variable name as argument print("The Object id of 'a' is: " + str(id(a))) </code></pre> <p><strong>输出:</strong></p> <p>以下输出表示</p> <pre><code class="language-py">The Object id of 'a' is: 1695893310240 </code></pre> <h2 id="什么是不变性">什么是不变性?</h2> <p>为了正确理解不变性的概念,我们需要知道可变对象和不可变对象之间的区别。</p> <h3 id="什么是可变对象">什么是可变对象?</h3> <p>如果一个对象的状态在它被创建后可以被改变,那么它被称为可变对象。</p> <p><strong>举例:</strong></p> <p>下面我们将下面的随机值列表分配给变量' <strong>randomValues</strong> '。一旦它被创建,我们检查并记下它的对象 ID。然后,我们需要修改列表(这可以通过追加值、删除值或简单地用其他值替换其中一个值来实现)。然后我们再次记下对象 ID。</p> <p>如果对象 ID /链表的存储位置保持不变,那么我们可以说 <a href="https://www.askpython.com/python/difference-between-python-list-vs-array" target="_blank">Python 链表</a>的状态已经改变。</p> <pre><code class="language-py"># Our list of random values randomValues = ["Bojack Horseman", 42, "Robert Langdon", 1.61803] id1 = id(randomValues) # Modifying/Changing the state of our list randomValues[1] = "The answer to everything" randomValues.append("I love Python") id2 = id(randomValues) # Compare the object id before and after modifying if id1 == id2: print("The Object ID Remains the same.") else: print("The Object ID changes.") </code></pre> <p>输出:</p> <pre><code class="language-py">The Object ID Remains the same. </code></pre> <p>正如我们所看到的,当值改变时,列表的内存位置或 ID 保持不变。这意味着 Python 为该位置分配了更多的内存空间来考虑额外的值。</p> <p>由此我们可以说列表是一个“可变的”对象或可变的对象。</p> <h3 id="什么是不可变对象">什么是不可变对象?</h3> <p>如果一个对象的状态在创建后不能改变,那么它就被称为不可变对象。</p> <p><strong>例 1:</strong></p> <p>与我们之前的例子不同,我们在操作中使用了列表,下面,我们用随机值初始化一个元组。然后我们记下它的对象 ID。接下来,我们尝试修改元组,并比较之前和之后的对象 id。</p> <pre><code class="language-py"># Our tuple of random values randomValues = ("Bojack Horseman", 42, "Robert Langdon", 1.61803) id1 = id(randomValues) # Modifying/Changing the state of our tuple randomValues[1] = "The answer to everything" # Compare the object id before and after modifying if id1 == id2: print("The Object ID Remains the same.") else: print("The Object ID changes.") </code></pre> <p>输出:</p> <pre><code class="language-py">TypeError: 'tuple' object does not support item assignment </code></pre> <p>这里我们看到 <a href="https://www.askpython.com/python/tuple/python-tuple" target="_blank">tuple</a> (一种固有的不可变类型)不支持修改它的值或向它们追加项目。所以,让我们用一个整数继续同样的操作。</p> <p><strong>例 2:</strong></p> <p>现在我们需要给任何变量分配一个简单的整数值,并记下它的对象 ID。像前面的例子一样,我们给整型变量赋一个新值,并比较对象 ID。</p> <pre><code class="language-py"># first we assign an integer value to the variable randomNumber = 42 id1 = id(randomNumber) # Change the value of our integer variable randomNumber = 134 id2 = id(randomNumber) if id1 == id2: print("The Object ID remains the same.") else: print("The Object ID changed.") </code></pre> <p>输出:</p> <pre><code class="language-py">The Object ID changed. </code></pre> <p>在这里,我们可以清楚地注意到,在新的值赋值之后,变量“randomNumber”的对象 id 也发生了变化。</p> <p>也就是说,它是一个独立的物体。这不是原始对象状态的改变。</p> <p><strong>注意:当你用一个不可变的对象给一个变量赋值时——这会创建一个新的对象,而不会覆盖当前的对象。</strong></p> <h3 id="python-中哪些对象是不可变的">Python 中哪些对象是不可变的?</h3> <p>现在我们已经理解了单词<strong>在 Python</strong> 中不可变的含义,让我们看看 Python 中哪些类型的对象是不可变的:</p> <ul> <li>用线串</li> <li>整数</li> <li>漂浮物</li> <li>元组</li> <li>范围是元组</li> </ul> <h2 id="结论-54">结论</h2> <p>不可变对象的一个主要好处是,它们比可变对象的访问速度快得多。希望这篇文章能帮助你理解 Python 中不可变对象的概念。</p> <h3 id="参考-8">参考</h3> <p><a href="https://docs.python.org/3/reference/datamodel.html" target="_blank">https://docs.python.org/3/reference/datamodel.html</a></p> <h1 id="导入错误-未找到名为-tensorflow-的模块已解决">导入错误-未找到名为 Tensorflow 的模块[已解决]</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/import-error-no-module-named-tensorflow-found" target="_blank">https://www.askpython.com/python/examples/import-error-no-module-named-tensorflow-found</a></p> </blockquote> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/860e414dc27d0b169aad98e67a96bd9b.png" alt="Error Message" loading="lazy"></p> <p>得到类似模块未找到的提示错误:没有名为' TensorFlow '的模块,就像我在 IDE 中得到的一样(Py-Charm)。别担心,我会掩护你的。我们开始吧。</p> <h2 id="找不到名为-tensorflow-的模块因为未安装该模块">找不到名为 Tensorflow 的模块,因为未安装该模块</h2> <p>如果 TensorFlow 模块没有安装在您的系统上,导入错误消息肯定会出现。那么,如何检查是否安装了 Tensorflow 模块呢?</p> <p>要进行检查,请在各自的操作系统中打开终端,并写下:</p> <pre><code class="language-py">pip show tensorflow </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/124929478435de776cba2532d0e6dc54.png" alt="WARNING-MESSAGE" loading="lazy"></p> <p>执行上述命令后,出现以下提示,这意味着需要安装 TensorFlow 包。</p> <h3 id="install-tensorflow">Install Tensorflow</h3> <p>Tensorflow 模块可通过执行以下步骤进行安装:</p> <p>TensorFlow 需要 pip 的<strong>最新版本</strong>,因此升级您的 pip 安装以确保您运行的是<strong>最新版本</strong>。</p> <pre><code class="language-py">pip install --upgrade pip </code></pre> <p>然后,用 pip 安装 TensorFlow</p> <pre><code class="language-py">pip install tensorflow </code></pre> <p>安装完成后,运行以下命令:</p> <pre><code class="language-py">pip show tensorflow </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/08ca975c5b722eecde7545b4db2664b5.png" alt="Tensorflow Version " loading="lazy"></p> <p>好了,你已经成功安装了 Tensorflow 模块。</p> <p>之后,安装模块有很少的机会,你得到一个导入错误信息。</p> <hr> <h3 id="python-解释器选择py-charm">Python 解释器选择–py charm</h3> <p>现在可能有另一种情况,模块已经安装在系统上,但仍然得到错误消息。</p> <p>我们中的许多人使用 PyCharm 作为 IDE 来编写 Python 程序。在 PyCharm 中创建新项目时,我们可以选择 Python 解释器。</p> <p>在这一步,PyCharm 为我们提供了两个选项,即使用新环境和之前配置的解释器。默认情况下,如果未选中<strong>继承全局站点包</strong>,则会设置第一个选项“新环境使用”,导致出现<strong>导入错误</strong>消息。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c98167c767cb5aac1f922d0dae333e88.png" alt="Inherit All Site Packages " loading="lazy"></p> <p>如果你在这个阶段,确保你选择了先前配置的解释器,点击<strong>添加解释器</strong>,然后给出 <strong>python</strong> <strong>的正确路径。exe</strong> 文件(小心操作)。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/9993b3c5e90f01fd1f03cc9b758e8823.png" alt="Interpreter-Popup-1" loading="lazy"></p> <p><strong>有关详细信息,请参阅下一节。</strong></p> <p>如果您在创建新项目时使用选择了选项<strong>新环境,那么不用担心,您可以通过以下步骤轻松更改解释器设置🙂</strong></p> <ul> <li> <p>转到 PyCharm IDE 左上角的<strong>文件</strong>选项,选择设置</p> </li> <li> <p>选择 <strong>Python 解释器</strong>并点击添加解释器</p> </li> </ul> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/61e473a3f71f3a8b3b01de5c7905f0e4.png" alt="Add Interpreter " loading="lazy"></p> <ul> <li>在<strong>系统解释器</strong>下,选择三个点给出 python.exe 文件的<strong>路径</strong></li> </ul> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cf945bda075d42f51e3ca6e5ce6635f3.png" alt="System-Interpreter" loading="lazy"></p> <ul> <li>给出<strong>python.exe</strong>文件的正确路径(<strong>仔细做好这一步</strong></li> </ul> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/2c54d325ef64b6e8ca8f67971566d2cc.png" alt="Interpreter Path" loading="lazy"></p> <ul> <li>很好,单击确定并应用更改</li> </ul> <p>以上是关于 PyCharm 中 Python 解释器设置的全部内容,希望对你的错误信息有所帮助。</p> <p>提示:如果你想继续使用 python 解释器的<strong>虚拟环境</strong>选项,只需<strong>勾选下图所示的框</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/159365ea3a220801370a44175773941c.png" alt="TIP" loading="lazy"></p> <hr> <h3 id="总结-2"><strong>总结</strong></h3> <p>务必确保不要用模块名创建 python 文件,如 tensorflow.py、pandas.py、matplotlib.py 等。这也导致了这些导入错误消息。确保您已经安装了该模块的最新版本。</p> <p>感谢阅读和快乐编码😀</p> <h1 id="补救在开源安全中的重要性">补救在开源安全中的重要性</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/resources/importance-of-remediation-in-open-source-security" target="_blank">https://www.askpython.com/resources/importance-of-remediation-in-open-source-security</a></p> </blockquote> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e4300cc55f463ff7edbde7f0bc0915ef.png" alt="Open Source Security" loading="lazy"></p> <p><strong>Photo by</strong> <a href="https://unsplash.com/@safarslife?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank"><strong>Safar Safarov</strong></a> <strong>on</strong> <a href="https://unsplash.com/s/photos/coding?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank"><strong>Unsplash</strong></a></p> <p>开源代码越来越受欢迎可以归因于这样一个事实,即开源项目本质上是协作性的和公共的。开源代码为开发人员提供了各种各样的优势,包括质量——因为他们能够轻松自由地使用代码,并可以根据自己的需要修改代码;速度——因为工具已经创建好了,开发人员只需要做很小的调整(如果有的话),然后合并它们;和降低项目成本。</p> <p>然而,它也有一些缺点,其中最显著的是安全性。开放源代码可能包含漏洞;许可问题;或者管理不当,所有这些都有可能影响组织的数据和安全并破坏组织的声誉。即使是现在,仍有一些项目是在很多年前开始的,但不再由任何人维护。因此,发现的任何安全缺陷都可能无法解决。</p> <p>因此,<a href="https://www.mend.io/open-source-security/" target="_blank">开源安全</a>是通过开源发布给公众的许多不同代码的重要组成部分。有必要对所有这些举措进行持续的补救,以确保它们没有漏洞,不会给本组织的安全带来风险。</p> <h2 id="为什么补救很重要"><strong>为什么补救很重要?</strong></h2> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7ea8ee8f12eb464f21852b9fe1f64989.png" alt="Remediation Process" loading="lazy"></p> <p>Source</p> <p>虽然不是所有的开源项目都是不安全的,但是那些在大量软件中广泛使用的项目正在被传播给大量的组织。即使是基于产品的组织最终也会继承大量的开源代码。</p> <p>在软件中使用任何开放源代码之前,必须进行开放源代码审查,以验证代码可以安全地包含在软件中,并确定项目或存储库是否得到维护。此审查还应确定软件是否正在更新。</p> <p>如果代码不安全或者存储库没有得到维护,那么在组织中包括这一点将不是一个好主意,因为将来可能出现的任何错误都没有任何可用的修复,组织将不得不自己寻找问题的解决方案。因此,需要进行开源审查,并且应该尽快解决发现的任何漏洞,以便保护组织及其基础设施。</p> <p>例如,由于在 Apache 的<a href="https://logging.apache.org/log4j/2.x/security.html" target="_blank">日志库</a>中发现的一个缺陷,整个互联网变得容易受到远程代码执行的影响。在这种情况下,补救措施对于确保组织的安全至关重要。</p> <p>补救甚至有助于提高软件或开发组件的生产率。随着开发人员的效率通过使用开源代码片段而提高,这些代码片段在修复过程中不再存在漏洞。开源组件的持续补救降低了与维护项目及其依赖项相关的成本,以及其他好处。所有这些步骤都将减少团队所需的工作量。</p> <h2 id="结论-55"><strong>结论</strong></h2> <p>由于如此多的公司使用开源代码或代码片段,越来越多的软件开发人员正集中精力解决开源软件中的安全缺陷。然而,公司可以通过进行代码审查来解决这些缺陷。</p> <p>内部代码应用程序的补救相对简单。另一方面,修复开源软件中的漏洞是一个巨大的挑战。所以,做好这件事很重要。除了增强整体安全性之外,补救还可以在提高项目完成效率方面发挥作用。因此,在使用任何开源项目之前,一定要验证它们包含什么样的漏洞,以及在使用它们之前是否有可能修复它们。</p> <h1 id="您必须知道的重要-python-selenium-函数">您必须知道的重要 Python Selenium 函数</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/important-python-selenium-functions" target="_blank">https://www.askpython.com/python-modules/important-python-selenium-functions</a></p> </blockquote> <p>在本教程中,我们将探索 selenium 最有用的方法。Selenium 提供了许多使自动化过程变得容易的方法,其中一些方法并不常见,但是对于使自动化/抓取过程变得容易和有效很有用。</p> <p><em><strong>也读作:<a href="https://www.askpython.com/python-modules/selenium-introduction-and-setup" target="_blank">安装设置硒</a></strong></em></p> <h2 id="导入模块并初始化-webdriver">导入模块并初始化 Webdriver</h2> <p>Selenium webdriver 是所有类和方法的父类。使用 webdriver,我们可以访问 selenium 提供的所有方法。</p> <pre><code class="language-py">from selenium import webdriver driver = webdriver.Chrome("path of webdriver") </code></pre> <p>代替“webdriver 的路径”,我们甚至可以只使用 Chrome()方法,而不传递 webdriver 的路径的任何位置参数,只要我们已经在我们的计算机中全局地将浏览器的 webdriver 的<strong>路径</strong>位置声明为<strong>环境变量</strong>。</p> <h2 id="python-selenium-中的浏览器方法">Python Selenium 中的浏览器方法</h2> <p>让我们从您最常使用并且应该很好掌握的浏览器方法开始。</p> <h3 id="1获取网页">1.获取网页</h3> <p>为了获取一个特定的网页,我们使用 <strong>get</strong> 方法,并将网页 URL 作为参数传递。</p> <pre><code class="language-py">driver.get("https://m.youtube.com") </code></pre> <h3 id="2获取网页标题">2.获取网页标题</h3> <p><strong>title</strong> 方法返回当前页面(网页)的标题,该标题打印在执行代码的控制台/终端上。</p> <pre><code class="language-py">driver.title() </code></pre> <h3 id="3在页面历史记录之间来回移动">3.在页面历史记录之间来回移动</h3> <p>通过使用<strong>后退</strong>和<strong>前进</strong>方法,我们可以在浏览器中自动执行后退或前进网页的任务</p> <pre><code class="language-py">driver.back() driver.forward() </code></pre> <h3 id="4全屏方法">4.全屏方法</h3> <p>调用此方法将使浏览器(chrome)窗口全屏显示。</p> <pre><code class="language-py">driver.fullscreen_window() </code></pre> <h3 id="5设置窗口在屏幕上的位置">5.设置窗口在屏幕上的位置</h3> <p>通过使用这种方法,您将能够设置当前窗口的坐标。该方法获取 x 和 y 坐标,并根据屏幕上的坐标在指定位置设置当前窗口(使用 python-selenium 代码打开)。</p> <pre><code class="language-py">driver.set_window_position(500,500) </code></pre> <p>屏幕位置的原点(0,0)位于屏幕的最底部左侧。</p> <h3 id="6打开一个新标签">6.打开一个新标签</h3> <p>要在新标签页上打开一个新网站,我们将使用 <strong>execute_script()</strong> 方法。在下面的例子中,代码将在我们的第一个网站 YouTube 旁边的新标签页中打开 Twitter。这个方法<strong>需要 JavaScript</strong> 来执行。</p> <pre><code class="language-py">driver.execute_script("window.open('https://twitter.com')") </code></pre> <h3 id="7截图">7.截图</h3> <p>Selenium 提供了一种获取当前窗口截图的方法。这是通过使用以下方法完成的</p> <pre><code class="language-py">driver.get_screenshot_as_file('ss.png') </code></pre> <p>运行此代码后,名为“ss”的图像将存储在同一目录中。</p> <h3 id="8刷新页面">8.刷新页面</h3> <p>通过使用 refresh 方法,我们可以刷新当前框架/网页。</p> <pre><code class="language-py">driver.refresh() </code></pre> <h3 id="9选择一个元素">9.选择一个元素</h3> <p>有各种方法和技术来选择元素、图像、文本字段、视频、标签等。在网页中。因此,我们已经在一篇单独的、详细的文章中介绍了选择元素的所有方法。</p> <p>推荐阅读:<a href="#">Selenium-Python 中选择元素的所有不同方式</a></p> <h3 id="10单击一个元素">10.单击一个元素</h3> <p>该方法用于点击 web 元素,如按钮或链接。</p> <p>在下面的代码中,我们首先使用其 ID 或任何其他选择器找到链接或按钮,然后在这个 web 元素上调用 click 方法。</p> <pre><code class="language-py">elements = driver.find_element_by_id("id of link or button") elements.click() </code></pre> <h3 id="11发送密钥文本">11.发送密钥(文本)</h3> <p>使用这种方法,我们可以将一些文本发送到网页中的任何文本字段。我们通过使用它的 id 找到 Gmail 的文本框,然后用 send_keys 方法发送我们的文本。</p> <pre><code class="language-py">elements = driver.find_element_by_id("gmail") elements.send_keys(“some text we want to send”) </code></pre> <h3 id="12清除文本">12.清除文本</h3> <p>它用于清除任何输入字段的文本。</p> <pre><code class="language-py">elements = driver.find_element_by_id("gmail") elements.send_keys("some text we want to send") elements.clear() </code></pre> <h3 id="13使用自定义-javascript">13.使用自定义 JavaScript</h3> <p>使用这种方法,我们可以发送定制的 JavaScript 代码,并对事件、<strong>提示</strong>等执行 JavaScript 支持的各种操作。</p> <pre><code class="language-py">driver.execute_script() #practical code implementation driver.execute_script("window.open('https://google.com')") </code></pre> <h3 id="14关闭当前选项卡但不关闭浏览器">14.关闭当前选项卡,但不关闭浏览器</h3> <p>通过使用 close 方法,我们可以在不关闭浏览器的情况下关闭<strong>当前选项卡。</strong></p> <pre><code class="language-py">driver.close() </code></pre> <h3 id="15关闭浏览器">15.关闭浏览器</h3> <p>我们可以用<strong>退出</strong>的方法关闭浏览器。显然,整个浏览器窗口关闭,关闭了所有打开的标签页。</p> <pre><code class="language-py">driver.quit() </code></pre> <h2 id="16时间-睡眠imp">16.时间-睡眠(Imp。)</h2> <p>这实际上不是与 Selenium 库相关联的功能或方法,但它是一个非常有用的技巧,对于各种目的都很方便,比如等待执行一些任务——加载站点、执行一些其他代码等。</p> <p>这是时间模块的一部分,它已经与我们的 python 安装捆绑在一起:</p> <pre><code class="language-py">import time #time.sleep(time to wait (in seconds)) time.sleep(5) #this will let the interpreter wait at this line for 5 seconds and then proceed with execution. </code></pre> <h2 id="结论-56">结论</h2> <p>教程到此为止。有各种各样的方法和功能与 Selenium 相关,其中一些您将在使用 Selenium 时自己学习,而另一些我们坚持要查看 Selenium 的官方<a href="https://www.selenium.dev/documentation/" target="_blank">文档</a>。</p> <h1 id="用-python-输入缺失的数据值3-种简单的方法">用 python 输入缺失的数据值——3 种简单的方法!</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/impute-missing-data-values" target="_blank">https://www.askpython.com/python/examples/impute-missing-data-values</a></p> </blockquote> <p>大家好!在本文中,我们将关注 Python 中估算缺失数据值的 <strong>3 个重要技术。</strong></p> <p>那么,让我们开始吧。</p> <hr> <h2 id="为什么我们需要估算缺失的数据值">为什么我们需要估算缺失的数据值?</h2> <p>在进行插补之前,让我们了解什么是缺失值。</p> <p>因此,缺失值是数据集看起来缺失的部分,或者是一个<a href="https://www.askpython.com/python/oops/python-none" target="_blank">空值</a>,可能是由于研究或数据收集过程中的一些缺失数据。</p> <p>机器学习模型中缺少值被认为是非常低效和危险的,原因如下:</p> <ul> <li><strong>降低 ML 模型的效率</strong>。</li> <li><strong>影响数据值的总体分布</strong>。</li> <li>它导致 ML 模型估计中的<strong>偏差效应</strong>。</li> </ul> <p>这就是归罪进入画面的时候。</p> <p>通过插补,我们的意思是用整个数据集中的特定值替换缺失值或空值。</p> <p>可以使用以下任何技术进行插补</p> <ul> <li><strong>通过平均值估算</strong></li> <li><strong>根据中位数估算</strong></li> <li><strong>Knn 插补</strong></li> </ul> <p>现在让我们理解并实现下一节中的每一项技术。</p> <hr> <h2 id="1通过平均值估算缺失数据值">1.通过平均值估算缺失数据值</h2> <p>缺失值可以用特定特征/数据变量的平均值来估算。也就是说,空值或缺失值可以替换为特定数据列或数据集的数据值的平均值。</p> <p>让我们看看下面的数据集,我们将在整篇文章中使用它。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1bd87576763691a8bcaa775e33904d65.png" alt="Dataset For Imputation" loading="lazy"></p> <p><strong>Dataset For Imputation</strong></p> <p>可以清楚地看到,上面的数据集包含空值。现在让我们试着用特征的平均值来估算它们。</p> <h3 id="导入所需的库">导入所需的库</h3> <p>首先,让我们将必要的数据集加载到工作环境中。</p> <pre><code class="language-py">#Load libraries import os import pandas as pd import numpy as np </code></pre> <p>我们已经使用 <a href="https://www.askpython.com/python-modules/python-csv-module" target="_blank">pandas.read_csv()函数</a>将数据集加载到环境中。</p> <pre><code class="language-py">marketing_train = pd.read_csv("C:/marketing_tr.csv") </code></pre> <h3 id="验证数据库中缺少的值">验证数据库中缺少的值</h3> <p>在输入缺失数据值之前,有必要使用如下所示的<code>isnull() function</code>来检查和检测缺失值的存在</p> <pre><code class="language-py">marketing_train.isnull().sum() </code></pre> <p>在执行上面的代码行之后,我们得到以下缺失值的计数作为输出:</p> <pre><code class="language-py">custAge 1804 profession 0 marital 0 responded 0 dtype: int64 </code></pre> <p>可以清楚地看到,数据变量“custAge”包含 7414 条记录中的 1804 条缺失值。</p> <h3 id="对所有空值使用-mean方法">对所有空值使用 mean()方法</h3> <p>此外,我们已经使用<code>mean() function</code>用列“custAge”的平均值估算所有空值。</p> <pre><code class="language-py">missing_col = ['custAge'] #Technique 1: Using mean to impute the missing values for i in missing_col: marketing_train.loc[marketing_train.loc[:,i].isnull(),i]=marketing_train.loc[:,i].mean() </code></pre> <h3 id="验证更改">验证更改</h3> <p>在用平均值进行插补后,让我们检查是否所有的值都被插补了。</p> <pre><code class="language-py">marketing_train.isnull().sum() </code></pre> <p>如下所示,所有缺失值都已估算,因此,我们看不到更多缺失值。</p> <pre><code class="language-py">custAge 0 profession 0 marital 0 responded 0 dtype: int64 </code></pre> <hr> <h2 id="2中位数插补">2.中位数插补</h2> <p>在这种技术中,我们用数据值或数据集的中值来估算缺失值。</p> <p>让我们通过下面的例子来理解这一点。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">#Load libraries import os import pandas as pd import numpy as np marketing_train = pd.read_csv("C:/marketing_tr.csv") print("count of NULL values before imputation\n") marketing_train.isnull().sum() missing_col = ['custAge'] #Technique 2: Using median to impute the missing values for i in missing_col: marketing_train.loc[marketing_train.loc[:,i].isnull(),i]=marketing_train.loc[:,i].median() print("count of NULL values after imputation\n") marketing_train.isnull().sum() </code></pre> <p>这里,我们使用<code>median() function</code>用中值估算缺失值。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">count of NULL values before imputation custAge 1804 profession 0 marital 0 responded 0 dtype: int64 count of NULL values after imputation custAge 0 profession 0 marital 0 responded 0 dtype: int64 </code></pre> <hr> <h2 id="3knn-插补">3.KNN 插补</h2> <p>在该技术中,缺失值基于 KNN 算法进行估算,即<strong>K-最近邻算法</strong>。</p> <p>在该算法中,缺失值由最近邻估计值代替。</p> <p>让我们用下面的例子来理解实现:</p> <p><strong>KNN 插补:</strong></p> <pre><code class="language-py">#Load libraries import os import pandas as pd import numpy as np marketing_train = pd.read_csv("C:/marketing_tr.csv") print("count of NULL values before imputation\n") marketing_train.isnull().sum() </code></pre> <p>这里是缺失值的计数:</p> <pre><code class="language-py">count of NULL values before imputation custAge 1804 profession 0 marital 0 responded 0 dtype: int64 </code></pre> <p>在下面这段代码中,我们已经将数据变量的数据类型转换为对象类型,并为它们分配了分类代码。</p> <pre><code class="language-py">lis = [] for i in range(0, marketing_train.shape[1]): if(marketing_train.iloc[:,i].dtypes == 'object'): marketing_train.iloc[:,i] = pd.Categorical(marketing_train.iloc[:,i]) #print(marketing_train[[i]]) marketing_train.iloc[:,i] = marketing_train.iloc[:,i].cat.codes marketing_train.iloc[:,i] = marketing_train.iloc[:,i].astype('object') lis.append(marketing_train.columns[i]) </code></pre> <p><code>KNN() function</code>用于用可能的最近邻估算缺失值。</p> <pre><code class="language-py">#Apply KNN imputation algorithm marketing_train = pd.DataFrame(KNN(k = 3).fit_transform(marketing_train), columns = marketing_train.columns) </code></pre> <p><strong>插补输出</strong>:</p> <pre><code class="language-py">Imputing row 1/7414 with 0 missing, elapsed time: 13.293 Imputing row 101/7414 with 1 missing, elapsed time: 13.311 Imputing row 201/7414 with 0 missing, elapsed time: 13.319 Imputing row 301/7414 with 0 missing, elapsed time: 13.319 Imputing row 401/7414 with 0 missing, elapsed time: 13.329 . . . . . Imputing row 7101/7414 with 1 missing, elapsed time: 13.610 Imputing row 7201/7414 with 0 missing, elapsed time: 13.610 Imputing row 7301/7414 with 0 missing, elapsed time: 13.618 Imputing row 7401/7414 with 0 missing, elapsed time: 13.618 </code></pre> <pre><code class="language-py">print("count of NULL values after imputation\n") marketing_train.isnull().sum() </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">count of NULL values before imputation custAge 0 profession 0 marital 0 responded 0 dtype: int64 </code></pre> <hr> <h2 id="结论-57">结论</h2> <p>到此,我们就结束了这个话题。在本文中,我们实现了 3 种不同的插补技术。</p> <p>如果你遇到任何问题,欢迎在下面评论。</p> <p>更多此类与 Python 相关的帖子,敬请关注@ <a href="https://www.askpython.com/" target="_blank">Python with AskPython</a> 继续学习!</p> <h1 id="python-中的in和not-in运算符">Python 中的“in”和“not in”运算符</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/in-and-not-in-operators-in-python" target="_blank">https://www.askpython.com/python/examples/in-and-not-in-operators-in-python</a></p> </blockquote> <p>嘿!所以今天我们要讨论 Python 中的“in”和“not in”操作符。</p> <h2 id="pythonin运算符">python“in”运算符</h2> <p>基本上,Python 中的<code>in</code>操作符检查一个指定的值是否是一个序列的组成元素,如<a href="https://www.askpython.com/python/string" target="_blank">字符串</a>、<a href="https://www.askpython.com/python/array/python-array-examples" target="_blank">数组</a>、<a href="https://www.askpython.com/python/list/python-list" target="_blank">列表</a>或<a href="https://www.askpython.com/python/tuple/python-tuple" target="_blank">元组</a>等。</p> <p>在条件中使用时,该语句返回一个布尔结果,评估为<code>True</code>或<code>False</code>。当指定值是在序列中找到的的<strong>时,语句返回<code>True</code>。而当没有找到</strong>时,我们得到一个<code>False</code>。</p> <p>让我们举个例子来更好地理解<code>in</code>操作符的工作原理。</p> <pre><code class="language-py">#in operator working list1= [1,2,3,4,5] string1= "My name is AskPython" tuple1=(11,22,33,44) print(5 in list1) #True print("is" in string1) #True print(88 in tuple1) #False </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1ebfd18cef13d87f18462018aed52597.png" alt="Python In Output" loading="lazy"></p> <p>Python in Output</p> <p>这里:</p> <p>首先,我们已经用一些值初始化了一个列表<code>list1</code>,一个字符串<code>string1</code>和一个元组<code>tuple1</code>。然后我们使用<code>in</code>操作符来检查一些值是否是上述序列的一部分。</p> <p>从上面的输出中我们可以看到,<code>5 in list1</code>评估为<strong>真</strong>。这表示在列表中找到了值 <strong>5</strong> 。</p> <p>类似地,使用<code>in</code>操作符,我们还确认了字符串<strong>“is”</strong>在<code>string1</code>中的存在。但是对于最后一种情况,该条件导致<strong>假</strong>,因为 <strong>88</strong> 不存在于序列<code>tuple1</code>中。</p> <h2 id="python不在运算符">Python“不在”运算符</h2> <p>Python 中的<code>not in</code>操作符与<code>in</code>操作符的工作方式完全相反。它还检查给定序列中指定值的存在,但是它的返回值与<code>in</code>操作符的完全相反。</p> <p>当在序列中存在指定值的条件下使用时,该语句返回<code>False</code>。反之,当它不是,我们得到一个<code>True</code>。</p> <p>让我们以前面的例子为例,只是将<code>in</code>操作符替换为<code>not in</code>操作符。</p> <pre><code class="language-py">#not in operator working list1= [1,2,3,4,5] string1= "My name is AskPython" tuple1=(11,22,33,44) print(5 not in list1) #False print("is" not in string1) #False print(88 not in tuple1) #True </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f438fe0dad66f3bed5b0f3ab578c4f73.png" alt="Not In Output" loading="lazy"></p> <p>not in Output</p> <p>正如所料,结果输出是我们之前使用<code>in</code>操作符得到的与相反的<strong>。</strong></p> <h2 id="python-字典中in和not-in运算符的使用">Python 字典中“in”和“not in”运算符的使用</h2> <p>之前我们讨论了<code>in</code>和<code>not in</code>操作符在不同类型序列上的工作。但是<a href="https://www.askpython.com/python/dictionary/python-dictionary-dict-tutorial" target="_blank">字典</a>不是序列。与它们不同,字典是基于<strong>键</strong>来索引的。</p> <p>那么上面的操作符对字典起作用吗?如果有,他们如何评估病情?</p> <p>让我们试着用一个例子来理解。</p> <pre><code class="language-py">#in and not in operator working on Dictionary dict1 = {1: "one", 2: "two", 3: "three", 4: "four"} print("one" in dict1) print("one" not in dict1) print(3 in dict1) print(3 not in dict1) print(5 in dict1) print(5 not in dict1) </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e78e56a6551ac5dcda6efd1e2f2481fd.png" alt="Using In And Not In On Dictionary" loading="lazy"></p> <p>Using in And not in on Dictionary</p> <p>首先,我们已经用某组<strong>键</strong>和相应的<strong>值</strong>初始化了字典<code>dict1</code>。</p> <p>正如我们从上面的输出中看到的,<code>"one" in dict1</code>评估为一个<strong>假</strong>。然而,<code>3 in dict1</code>给了我们<strong>真</strong>。</p> <p>所以很明显,in 操作符在字典<strong>键</strong>中寻找元素,而不是<strong>值</strong>。因此,类似地,最后一个语句<code>5 in dict1</code>也导致<strong>假</strong>,因为它不是字典中的键。</p> <p>如前所述,这里的<code>not in</code>操作符也以同样的方式进行计算。</p> <h2 id="结论-58">结论</h2> <p>所以在本教程中,我们学习了 Python 中的<code>in</code>和<code>not in</code>操作符,以及它们在一些例子中的工作。</p> <p>如有任何进一步的问题,欢迎使用下面的评论。</p> <h2 id="参考-9">参考</h2> <ul> <li>Python“在”和“不在”成员操作符——期刊开发帖子,</li> <li><a href="https://stackoverflow.com/questions/45707721/how-does-the-in-and-not-in-statement-work-in-python" target="_blank">python 中的“in”和“not in”语句如何工作</a>–stack overflow 问题。</li> </ul> <h1 id="将索引转到熊猫数据框架中的列">将索引转到熊猫数据框架中的列</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/pandas/index-to-column-dataframe" target="_blank">https://www.askpython.com/python-modules/pandas/index-to-column-dataframe</a></p> </blockquote> <p>你好。在本 Python 教程中,我们将讨论如何将数据帧索引转换为列。我们还将看到如何将多索引数据帧的多级索引转换成它的多列。所以让我们开始吧。</p> <hr> <h2 id="熊猫数据框架中的索引是什么">熊猫数据框架中的索引是什么?</h2> <p>Pandas 是一个健壮的 Python 库,广泛用于数据分析。它为我们提供了一个名为 <strong>DataFrame</strong> 的数据结构,以行和列的形式存储数据,其中每一行都有一个唯一的索引值。一个 pandas DataFrame 对象可以有一个以上的索引级别,在这种情况下,它被称为多索引 DataFrame。</p> <p>每当我们创建一个 panda DataFrame 对象时,默认情况下,从<strong>零</strong>到<strong>行数–1</strong>的索引值按顺序分配给 DataFrame 的每一行。尽管我们也可以使用 pandas 中的<code>DataFrame.set_index()</code>函数为 pandas DataFrame 对象的每一行手动设置索引值。</p> <p>我们可以使用以下两种方法将 pandas DataFrame 对象的一级或多级索引转换成它的列。为了演示将 DataFrame 索引转换为列的过程,让我们首先创建一个 pandas DataFrame 对象。</p> <p><em><strong>也读作:<a href="https://www.askpython.com/python-modules/pandas/dataframe-indexing" target="_blank">熊猫数据帧索引:设置一个熊猫数据帧的索引</a></strong></em></p> <h2 id="熊猫数据框中索引到列的转换方法">熊猫数据框中索引到列的转换方法</h2> <pre><code class="language-py"># Import pandas Python module import pandas as pd # Create a pandas DataFrame object df = pd.DataFrame({'Dept': ['ECE', 'ICE', 'IT', 'CSE', 'CHE'], 'GPA': [8.15, 9.03, 7.85, 8.55, 9.45], 'Name': ['Kirti', 'Sarthak', 'Anubhav', 'Ranjan', 'Kartik'], 'RegNo': [111, 112, 113, 114, 115]}) # Set 'RegNo' as index of the pandas DataFrame df.set_index('RegNo', inplace=True) # Print the created pandas DataFrame object print('Sample pandas DataFrame:\n') print(df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Sample pandas DataFrame: Dept GPA Name RegNo 111 ECE 8.15 Kirti 112 ICE 9.03 Sarthak 113 IT 7.85 Anubhav 114 CSE 8.55 Ranjan 115 CHE 9.45 Kartik </code></pre> <h3 id="方法-1创建一个新的-dataframe-列并传递索引">方法 1:创建一个新的 DataFrame 列并传递索引</h3> <p>这是将 DataFrame 索引转换为列的最简单方法。在这个方法中,我们简单地在 DataFrame 中创建一个新列,并使用 pandas DataFrame 类的<code>DataFrame.index</code>方法将索引传递给它。让我们看看实现这个方法的 Python 代码。</p> <pre><code class="language-py"># Method 1 # Convert the index of the sample DataFrame into column # Using the new column method df['Roll'] = df.index # Print the modified pandas DataFrame print('Modified pandas DataFrame:\n') print(df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Modified pandas DataFrame: Dept GPA Name Roll RegNo 111 ECE 8.15 Kirti 111 112 ICE 9.03 Sarthak 112 113 IT 7.85 Anubhav 113 114 CSE 8.55 Ranjan 114 115 CHE 9.45 Kartik 115 </code></pre> <h3 id="方法-2在-pandas-中使用-dataframereset_index函数">方法 2:在 pandas 中使用 DataFrame.reset_index()函数</h3> <p>这是将一个或多个级别的 DataFrame 索引转换为一个或多个列的广泛使用的方法。在这个方法中,我们将使用 pandas DataFrame 类的<code>DataFrame.reset_index()</code>函数。让我们编写 Python 代码来实现这个方法。</p> <pre><code class="language-py"># Method 2 # Convert the index of the sample DataFrame into column # Using the DataFrame.reset_index() function df.reset_index(inplace=True) # Print the modified pandas DataFrame print('Modified pandas DataFrame:\n') print(df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Modified pandas DataFrame: RegNo Dept GPA Name 0 111 ECE 8.15 Kirti 1 112 ICE 9.03 Sarthak 2 113 IT 7.85 Anubhav 3 114 CSE 8.55 Ranjan 4 115 CHE 9.45 Kartik </code></pre> <h2 id="将多索引数据框架的一个或多个级别转换为列">将多索引数据框架的一个或多个级别转换为列</h2> <p>让我们首先通过使用<code>DataFrame.set_index()</code>函数将<code>RegNo</code>和<code>Name</code>设置为样本数据帧的多级索引,将上述样本数据帧转换为多索引数据帧。</p> <pre><code class="language-py"># Convert the sample DataFrame into MultiIndex DataFrame # By setting the 'RegNo' and 'Name' as Multi-level index df.set_index(['RegNo', 'Name'], inplace=True) # Print the modified pandas DataFrame print('Modified Sample pandas DataFrame:\n') print(df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Modified Sample pandas DataFrame: Dept GPA RegNo Name 111 Kirti ECE 8.15 112 Sarthak ICE 9.03 113 Anubhav IT 7.85 114 Ranjan CSE 8.55 115 Kartik CHE 9.45 </code></pre> <p>现在让我们编写 Python 代码,使用<code>DataFrame.reset_index()</code>函数将示例多索引数据帧中的一个索引级别转换成一个列。</p> <pre><code class="language-py"># Convert one level of the MultiIndex DataFrame into column # Using the DataFrame.reset_index() function df.reset_index(level='Name', inplace=True) # Print the modified pandas DataFrame print('Modified pandas DataFrame:\n') print(df) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Modified pandas DataFrame: Name Dept GPA RegNo 111 Kirti ECE 8.15 112 Sarthak ICE 9.03 113 Anubhav IT 7.85 114 Ranjan CSE 8.55 115 Kartik CHE 9.45 </code></pre> <h2 id="总结-3">总结</h2> <p>在本教程中,我们学习了如何将熊猫数据帧的索引转换成它的列。我们还学习了将多索引数据帧的一个或多个级别的索引转换成它的列。希望你已经理解了上面讨论的东西,并准备好用你自己的熊猫数据框架进行实验。感谢阅读!请继续关注我们,了解更多与 Python 编程相关的精彩学习内容。</p> <h1 id="python-中的索引初学者完全指南">Python 中的索引——初学者完全指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/list/indexing-in-python" target="_blank">https://www.askpython.com/python/list/indexing-in-python</a></p> </blockquote> <p>Python 中的索引是什么?–尽管看起来很简单,但是正确解释 Python 中的索引工作方式可能会有点棘手。因此,请坐下来阅读我们的文章,以便更深入地理解 Python 中的索引。</p> <h2 id="先决条件-什么是可迭代的">先决条件-什么是可迭代的?</h2> <p>在开始索引之前,我们先了解一下 <a href="https://www.askpython.com/python/built-in-methods/python-iterator" target="_blank">iterables</a> 是什么,它们的主要功能是什么。索引背后非常需要可重复项的知识。</p> <p><strong>那么什么是可迭代的?</strong></p> <p>它是 Python 中一种特殊类型的<a href="https://www.askpython.com/python/oops/python-classes-objects" target="_blank">对象,您可以对其进行迭代。这意味着您可以遍历对象中包含的所有不同元素或实体。使用循环</a>的<a href="https://www.askpython.com/python/python-for-loop" target="_blank">可以轻松实现。</a></p> <p>在这种情况下,所有这些可迭代项所携带的是两个叫做 <strong>iter</strong>()或 <strong>getitem</strong>()的特殊方法,它们实现了 <em><strong>序列语义</strong></em> 。</p> <pre><code class="language-py">#Lists are iterable items in Python. randomItems = [4, 6, 2, 56, 23, 623, 453] #Each individual element inside a list can be accessed using a for loop for item sin randomItems: print(item) </code></pre> <p>除了列表,字符串和元组在 Python 中也是可迭代的。这是一个如何迭代字符串的例子。</p> <pre><code class="language-py">title = "Lose Yourself" #Looping through each character in the string for char in title: print(char) </code></pre> <p>输出:</p> <pre><code class="language-py">L o s e Y o u r s e l f </code></pre> <p>现在我们对 Python 中的可迭代对象有了一些了解。这与索引有什么关系?</p> <h2 id="python-中的索引是什么">Python 中的索引是什么?</h2> <p>Python 中的索引是一种通过位置引用 iterable 中单个项的方法。换句话说,您可以在 iterable 中直接访问您选择的元素,并根据您的需要进行各种操作。</p> <p>在我们讨论 Python 中的索引示例之前,有一件重要的事情需要注意:</p> <p>在 Python 中,对象是“零索引”的,这意味着位置计数从零开始。许多其他编程语言遵循相同的模式。事实上,你们中的许多人应该已经对它很熟悉了,因为它在互联网上在模因文化中很流行。</p> <p>如果一个列表中有 5 个元素。则第一个元素(即最左边的元素)保持“第零”位置,随后是第一、第二、第三和第四位置的元素。</p> <pre><code class="language-py">fruits = ["apple", "grape", "orange", "guava", "banana"] #Printing out the indexes of Apples and Banana print("Index of Apple: ", fruits.index("apple")) print("Index of Banana: ", fruits.index("banana")) </code></pre> <p>输出:</p> <pre><code class="language-py">Index of Apple: 0 Index of Banana: 4 </code></pre> <p>当对列表调用 index()方法并将项目名称作为参数传递时,可以显示列表中特定项目的索引。</p> <p>在下一节中,我们最终将学习如何在 iterable 对象上使用 index()方法。</p> <h3 id="什么是-python-索引运算符">什么是 Python 索引运算符?</h3> <p>Python 索引运算符由左右方括号表示:[]。但是,语法要求您在括号内输入一个数字。</p> <h3 id="python-索引运算符语法">Python 索引运算符语法</h3> <pre><code class="language-py">ObjectName[n] #Where n is just an integer number that represents the position of the element we want to access. </code></pre> <h2 id="在-python-中使用索引的步骤">在 Python 中使用索引的步骤</h2> <p>下面,我们将找出在 Python 中使用索引的例子。</p> <h3 id="1索引字符串">1.索引字符串</h3> <pre><code class="language-py">greetings = "Hello, World!" print(greetings[0]) #Prints the 0-th element in our string print(greetings[5]) #Prints the 5-th element in our string print(greetings[12]) #Prints the 12-th element in our string </code></pre> <p>输出:</p> <pre><code class="language-py">H , ! </code></pre> <p>我们可以清楚地看到我们的 print 函数是如何访问 string 对象中的不同元素来获得我们想要的特定字符的。</p> <h3 id="2python-中的负索引">2.Python 中的负索引</h3> <p>我们最近学习了如何在列表和字符串中使用索引来获取我们感兴趣的特定项目。尽管在我们之前的所有例子中,我们在索引操作符(方括号)中使用了正整数,但这并不是必须的。</p> <p>通常,如果我们对列表的最后几个元素感兴趣,或者我们只想从相反的一端索引列表,我们可以使用负整数。这种从另一端转位的过程称为负转位。</p> <p><strong>注意:在负索引中,最后一个元素用-1 而不是-0 表示。</strong></p> <pre><code class="language-py">letters = ['a', 's', 'd', 'f'] #We want to print the last element of the list print(letters[-1]) #Notice we didn't use -0 #To print the 2nd last element from an iterable print(letters[-2]) </code></pre> <p>输出:</p> <pre><code class="language-py">f d </code></pre> <h2 id="结论-59">结论</h2> <p>希望您喜欢我们的文章,并学会了如何在自己的代码中使用索引。快乐编码。</p> <h1 id="python-中的无穷大将-python-变量值设置为无穷大">Python 中的无穷大–将 Python 变量值设置为无穷大</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/infinity-in-python" target="_blank">https://www.askpython.com/python/examples/infinity-in-python</a></p> </blockquote> <p>一个简单的数字不能代表你的数据集?在 Python 中把你的变量值设置为无穷大怎么样?今天我们要说的就是这个!</p> <p>在用 Python 编码时,我们经常需要用一个大的正值或大的负值来初始化一个变量。这在比较变量以计算集合中的最小值或最大值时非常常见。</p> <p><strong>Python 中的正无穷大</strong>被认为是最大的正值,<strong>负无穷大</strong>被认为是最大的负数。</p> <p>在本教程中,我们将学习用正负无穷大初始化变量的三种方法。除此之外,我们还将学习如何检查一个变量是否无穷大,并对这些变量执行一些算术运算。</p> <p>让我们开始吧。</p> <h2 id="在-python-中用无穷大初始化浮点变量">在 Python 中用无穷大初始化浮点变量</h2> <p>在不使用任何模块的情况下,将变量设置为正无穷大或负无穷大的最简单方法是使用 <a href="https://www.askpython.com/python/built-in-methods/python-float-method" target="_blank">float</a> 。</p> <p>您可以使用以下代码行将变量设置为正无穷大:</p> <pre><code class="language-py">p_inf = float('inf') </code></pre> <p>要打印变量值,请使用:</p> <pre><code class="language-py">print('Positive Infinity = ',p_inf) </code></pre> <p>输出:</p> <pre><code class="language-py">Positive Infinity = inf </code></pre> <p>要用负无穷大初始化变量,请使用:</p> <pre><code class="language-py">n_inf = float('-inf') print('Negative Infinity = ',n_inf) </code></pre> <p>输出:</p> <pre><code class="language-py">Negative Infinity = -inf </code></pre> <h2 id="使用-numpy-模块初始化具有无穷大的变量">使用 Numpy 模块初始化具有无穷大的变量</h2> <p>你也可以使用流行的 <a href="https://www.askpython.com/python-modules/numpy/python-numpy-module" target="_blank">Numpy 模块</a>来初始化具有正或负无穷大的变量。</p> <p>让我们从导入 Numpy 模块开始。</p> <pre><code class="language-py">import Numpy as np </code></pre> <p>现在,我们可以使用模块将变量初始化为正无穷大,如下所示:</p> <pre><code class="language-py">p_inf = np.inf print('Positive Infinity = ',p_inf) </code></pre> <p>输出结果如下:</p> <pre><code class="language-py">Positive Infinity = inf </code></pre> <p>要用负无穷大初始化变量,请使用:</p> <pre><code class="language-py">n_inf = -np.inf print('Negative Infinity = ',n_inf) </code></pre> <p>输出结果如下:</p> <pre><code class="language-py">Negative Infinity = -inf </code></pre> <h3 id="完全码">完全码</h3> <p>下面给出了本节的完整代码。</p> <pre><code class="language-py">import Numpy as np #positive inf p_inf = np.inf print('Positive Infinity = ',p_inf) #negative inf n_inf = -np.inf print('Negative Infinity = ',n_inf) </code></pre> <h2 id="使用数学模块在-python-中用无穷大初始化变量">使用数学模块在 Python 中用无穷大初始化变量</h2> <p>将变量初始化为无穷大的第三种方法是使用 python 中的<a href="https://www.askpython.com/python-modules/python-math-module" target="_blank">数学模块</a>。</p> <p>让我们从导入模块开始。</p> <pre><code class="language-py">import math </code></pre> <p>要使用数学模块将变量设置为正无穷大,请使用以下代码行:</p> <pre><code class="language-py">p_inf = math.inf print('Positive Infinity = ',p_inf) </code></pre> <p>输出:</p> <pre><code class="language-py">Positive Infinity = inf </code></pre> <p>要使用数学模块将变量设置为负无穷大,请使用以下代码行:</p> <pre><code class="language-py">n_inf = -math.inf print('Negative Infinity = ',n_inf) </code></pre> <p>输出:</p> <pre><code class="language-py">Negative Infinity = -inf </code></pre> <p>除此之外,Math 模块还给出了一个方法,让你检查一个变量是否被设置为无穷大。</p> <p>您可以使用下面一行代码来检查它:</p> <pre><code class="language-py">math.isinf(p_inf) </code></pre> <p>输出:</p> <pre><code class="language-py">True </code></pre> <pre><code class="language-py">math.isinf(n_inf) </code></pre> <p>输出:</p> <pre><code class="language-py">True </code></pre> <h3 id="完全码-1">完全码</h3> <p>本节的完整代码如下所示:</p> <pre><code class="language-py">import math #positive inf p_inf = math.inf print('Positive Infinity = ',p_inf) #negative inf n_inf = -math.inf print('Negative Infinity = ',n_inf) #check print(math.isinf(p_inf)) print(math.isinf(n_inf)) </code></pre> <h2 id="python-中关于无穷大的算术运算">Python 中关于无穷大的算术运算</h2> <p>让我们试着用设置为正负无穷大的变量做一些算术运算。</p> <h3 id="1对无穷大值的加法运算">1.对无穷大值的加法运算</h3> <p>让我们看看当我们把一个数加到正无穷大和负无穷大时会发生什么。</p> <pre><code class="language-py">a = p_inf + 100 print(a) </code></pre> <p>输出:</p> <pre><code class="language-py">inf </code></pre> <pre><code class="language-py">a = n_inf + 100 print(a) </code></pre> <p>输出:</p> <pre><code class="language-py">-inf </code></pre> <h3 id="2无穷大值的减法">2.无穷大值的减法</h3> <p>让我们试着从正负无穷大中减去一个数。</p> <pre><code class="language-py">a = p_inf - 100 print(a) </code></pre> <p>输出:</p> <pre><code class="language-py">inf </code></pre> <pre><code class="language-py">a = n_inf - 100 print(a) </code></pre> <p>输出:</p> <pre><code class="language-py">-inf </code></pre> <p>我们可以看到,在无穷大上加上或减去一个值没有任何影响。</p> <p>让我们看看当我们在两个无穷大之间执行算术运算时会发生什么。</p> <h3 id="3两个无穷大之间的算术运算">3.两个无穷大之间的算术运算</h3> <p>让我们试着把正负无穷大相加,看看结果。</p> <pre><code class="language-py">a = p_inf + n_inf print(a) </code></pre> <p>输出:</p> <pre><code class="language-py">nan </code></pre> <p>我们得到的输出是 <strong>nan</strong> ,它是<strong>的缩写,而不是一个数字</strong>。因此,我们可以说这个操作没有被很好地定义。要了解南更多,请阅读这个<a href="https://www.askpython.com/python/examples/nan-in-numpy-and-pandas" target="_blank">教程。</a></p> <p>让我们看看正负无穷大相乘会发生什么。</p> <pre><code class="language-py">a = p_inf * n_inf print(a) </code></pre> <p>输出:</p> <pre><code class="language-py">-inf </code></pre> <p>我们得到负的无穷大,因为数值相乘,符号是负的,因为负的无穷大。</p> <p>让我们看看当我们在正负无穷大之间进行除法运算时会发生什么。</p> <pre><code class="language-py">a = p_inf / n_inf print(a) </code></pre> <p>输出:</p> <pre><code class="language-py">nan </code></pre> <p>无限除以无限也没有定义,因此我们得到 nan。</p> <h2 id="结论-60">结论</h2> <p>本教程是关于用正负无穷大初始化变量的不同方法。我们还讲述了一些涉及正负无穷大的算术运算。</p> <h1 id="python-中的继承">Python 中的继承</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/oops/inheritance-in-python" target="_blank">https://www.askpython.com/python/oops/inheritance-in-python</a></p> </blockquote> <h2 id="传承一目了然">传承一目了然!</h2> <p>在面向对象编程(OOP)的世界中,继承指的是一个类在运行中从另一个类派生或扩展属性的能力机制。该属性使派生类能够获取基类的属性或特征。</p> <p>继承被认为是 OOP 最重要的方面之一,因为它提供了<strong>可重用性</strong>的特性,从而使代码更加可靠。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/db669cfa86de71f215e653cb111508f6.png" alt="Python Inheritance" loading="lazy"></p> <p>Python Inheritance</p> <hr> <h2 id="继承的好处">继承的好处</h2> <ul> <li>继承描述了类似真实世界场景的关系。</li> <li>它提供了可重用的特性,允许用户在不改变派生类的情况下向其添加更多的特性。</li> <li>如果一个类 Y 继承自类 X,那么 Y 的所有子类都会自动继承自类 X。</li> </ul> <hr> <h2 id="遗传的基本术语">遗传的基本术语</h2> <ol> <li><em>子类/派生类</em>:是从另一个类(通常是基类)继承属性的类。</li> <li><em>超类/基类</em>:是衍生其他子类的类。</li> <li>派生类通常<em>派生/继承/扩展</em>基类。</li> </ol> <hr> <h2 id="python-继承语法">Python 继承语法</h2> <pre><code class="language-py">class SuperClassName: Body of Super class class DerivedClass_Name(SuperClass): Body of derived class </code></pre> <hr> <h2 id="python-继承示例">Python 继承示例</h2> <p>让我们通过简单的例子深入 Python 中的继承世界。</p> <h3 id="步骤-1创建一个基类">步骤 1:创建一个基类</h3> <pre><code class="language-py">class Father: # The keyword 'self' is used to represent the instance of a class. # By using the "self" keyword we access the attributes and methods of the class in python. # The method "__init__" is called as a constructor in object oriented terminology. # This method is called when an object is created from a class. # it allows the class to initialize the attributes of the class. def __init__(self, name, lastname): self.name = name self.lastname = lastname def printname(self): print(self.name, self.lastname) # Use the Father class to create an object, and then execute the printname method: x = Father("Anees", "Mulani") x.printname() </code></pre> <p><strong>输出</strong> : Anees Mulani</p> <hr> <h3 id="步骤-2创建派生类">步骤 2:创建派生类</h3> <pre><code class="language-py"># The subclass __init__() function overrides the inheritance of the base class __init__() function. class Son(Father): def __init__(self, name, lastname): Father.__init__(self, name, lastname) x = Son("Dev", "Bajaj") x.printname() </code></pre> <p><strong>输出</strong> : Dev Bajaj</p> <hr> <h2 id="super函数的使用">super()函数的使用</h2> <p>通过使用<code>super()</code>函数,您不必使用父元素的名称,它将自动从其父元素继承方法和属性。</p> <pre><code class="language-py">class Father: def __init__(self, name, lastname): self.name = name self.lastname = lastname def printname(self): print(self.name, self.lastname) class Son(Father): def __init__(self, name, lastname): super().__init__(name, lastname) x = Student("Dev", "Bajaj") x.printname() </code></pre> <p><strong>输出</strong> : Dev Bajaj</p> <hr> <h2 id="参考资料">参考资料:</h2> <ul> <li>JournalDev 上的 Python 继承</li> <li><a href="https://docs.python.org/3/tutorial/classes.html#inheritance" target="_blank">Python.org 文件</a></li> </ul> <h1 id="了解-python-中的-init方法">了解 Python 中的 <strong>init</strong>()方法</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/oops/init-method" target="_blank">https://www.askpython.com/python/oops/init-method</a></p> </blockquote> <p>在本文中,我们讨论 OOPs 的概念——<a href="https://www.askpython.com/python/oops/python-class-constructor-init-function" target="_blank">Python 构造函数</a>,并详细解释如何使用 <strong>init</strong>()方法初始化对象。</p> <h2 id="什么是构造函数">什么是构造函数?</h2> <p>在我们进入构造函数的概念之前,这里有一个关于类和对象的快速介绍:</p> <p><em>“在 OOP 中,object 是指开发者创建的抽象数据类型。对象由其参数(状态值)和行为(方法)定义/表征。类是构建特定类型对象的蓝图或一组指令。</em></p> <p>构造函数可以非常简单地理解为在对象初始化/创建期间调用的特殊方法。构造函数通常被定义为类定义中的一个函数,它接受状态参数并使用这些用户定义的参数创建一个对象。</p> <p>在 python 中,构造函数方法是 <strong>init</strong>(),编写为:</p> <pre><code class="language-py">def __init__(self, object_parameters...): # Initialize the object </code></pre> <p>该函数将 self 和对象参数作为输入。顾名思义,对象参数是定义对象的状态变量。</p> <p>“self”是 python 中的保留关键字,表示类的实例。“self”关键字允许轻松访问该类的方法和参数,以便在该类的其他方法中使用。</p> <p>例如,可以使用 self.var 访问对象状态变量“var”</p> <p>当我们看到创建类的例子时,这个想法会变得更加清晰。</p> <h2 id="创建一个简单的类笛卡尔点">创建一个简单的类:笛卡尔点</h2> <p>在这个例子中,我们为 2D 笛卡尔点的类创建了一个类。这个类有两个状态变量——x 和 y,它们定义了点的位置。</p> <pre><code class="language-py">class Point: def __init__(self, x, y): self.x = x self.y = y def coords(self): print("The point is at: ({}, {})".format(self.x, self.y)) </code></pre> <p><strong>init</strong>()方法将 self 和两个状态变量作为输入。然后,我们通过将对象的状态变量设置为用户定义的值来初始化对象。</p> <p>对象的状态变量(这里是 x 和 y)可以分别使用 self.x 和 self.y 来访问。</p> <p>这里的另一个方法是 coords(),它打印点的当前位置。注意我们如何使用 self.x 和 self.y 访问这些点。</p> <pre><code class="language-py"># Create object `P` of class Point with value 3 and 4 P = Point1(3, 4) # Print the coordinates of point `P` P.coords() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c4a287ac4bc3edcf9567f51077d2e986.png" alt="Image 23" loading="lazy"></p> <h2 id="init方法中的默认变量"><strong>init</strong>()方法中的默认变量</h2> <p>像 python 中的任何其他函数一样,<strong>init</strong>()方法允许您使用默认值。当一个类接受大量输入参数时,这个特性特别有用。这里我们构造了另一个类 Point1,如果没有指定数据点,它将 Point 初始化为(0,0)。</p> <pre><code class="language-py">class Point1: def __init__(self, x=0, y=0): self.x = x self.y = y def coords(self): print("The point is at: ({}, {})".format(self.x, self.y)) # Create object of class Point1 with default parameters Q = Point1() Q.coords() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/502fdb2d67d4f52103843bbf985f13c8.png" alt="Image 22" loading="lazy"></p> <h2 id="结论-61">结论</h2> <p>我们已经看到了如何为 python 类定义构造函数。虽然是最可行和最简单的方法,但事实证明这不是唯一的方法。Python 允许更复杂的类初始化,这在继承/扩展其他类时尤其重要。我们将在以后的文章中看到更多这样的例子。</p> <h1 id="三种初始化-python-数组的方法">三种初始化 Python 数组的方法</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/array/initialize-a-python-array" target="_blank">https://www.askpython.com/python/array/initialize-a-python-array</a></p> </blockquote> <p>嘿,伙计们!在本文中,我们将关注初始化 Python 数组的一些<strong>简单方法。</strong></p> <hr> <h2 id="什么是-python-数组">什么是 Python 数组?</h2> <p><strong>Python 数组</strong>是一种数据结构,在连续的内存位置保存相似的数据值。</p> <p>与<a href="https://www.askpython.com/python/list/python-list" target="_blank">列表</a>(动态数组)相比,Python 数组在其中存储了相似类型的元素。而 Python 列表可以存储属于不同数据类型的元素。</p> <p>现在,让我们看看在 Python 中初始化数组的不同方法。</p> <hr> <h2 id="方法-1使用-for-循环和-python-range函数">方法 1:使用 for 循环和 Python range()函数</h2> <p><a href="https://www.askpython.com/python/python-for-loop" target="_blank">Python for 循环</a>和 range()函数一起可以用来用默认值初始化一个数组。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">[value for element in range(num)] </code></pre> <p><a href="https://www.askpython.com/python/built-in-methods/python-range-method" target="_blank">Python range()函数</a>接受一个数字作为参数,返回一个数字序列,从 0 开始,到指定的数字结束,每次递增 1。</p> <p>Python for loop 会将数组中位于 range()函数中指定的范围之间的每个元素的值设置为 0(默认值)。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">arr=[] arr = [0 for i in range(5)] print(arr) </code></pre> <p>我们创建了一个数组“arr ”,并用带有默认值(0)的 5 个元素初始化它。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">[0, 0, 0, 0, 0] </code></pre> <hr> <h2 id="方法-2-python-numpy-模块创建并初始化数组">方法 2: Python NumPy 模块创建并初始化数组</h2> <p><a href="https://www.askpython.com/python-modules/numpy/python-numpy-arrays" target="_blank">Python NumPy 模块</a>可以用来创建数组并高效地操作数组中的数据。numpy.empty()函数创建一个指定大小的数组,默认值为“None”。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">numpy.empty(size,dtype=object) </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">import numpy as np arr = np.empty(10, dtype=object) print(arr) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">[None None None None None None None None None None] </code></pre> <hr> <h2 id="方法-3初始化-python-数组的直接方法">方法 3:初始化 Python 数组的直接方法</h2> <p>声明数组时,我们可以使用下面的命令初始化数据值:</p> <pre><code class="language-py">array-name = [default-value]*size </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">arr_num = [0] * 5 print(arr_num) arr_str = ['P'] * 10 print(arr_str) </code></pre> <p>如上面的例子所示,我们已经创建了两个数组,默认值为“0”和“P ”,以及指定的大小。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">[0, 0, 0, 0, 0] ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'] </code></pre> <hr> <h2 id="结论-62">结论</h2> <p>到此,我们就结束了这个话题。如果你有任何疑问,请随时在下面评论。</p> <hr> <h2 id="参考-10">参考</h2> <ul> <li><a href="https://numpy.org/doc/stable/reference/routines.array-creation.html" target="_blank">Python 数组初始化—文档</a></li> </ul> <h1 id="如何在-pytorch-中初始化模型权重">如何在 PyTorch 中初始化模型权重</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/initialize-model-weights-pytorch" target="_blank">https://www.askpython.com/python-modules/initialize-model-weights-pytorch</a></p> </blockquote> <p>知道如何初始化模型权重是<a href="https://www.askpython.com/python/examples/standardize-data-in-python" target="_blank">深度学习</a>的重要课题。初始权重影响很多因素——梯度、输出子空间等。在本文中,我们将了解一些最重要和最广泛使用的权重初始化技术,以及如何使用 <a href="https://www.askpython.com/python-modules/pytorch" target="_blank">PyTorch</a> 实现它们。本文希望用户对 PyTorch 有初级的熟悉程度。</p> <h2 id="为什么初始化模型权重很重要">为什么初始化模型权重很重要?</h2> <p>训练任何深度学习模型的目标都是找到模型的最佳权重集,从而给出我们想要的结果。深度学习中使用的训练方法通常在本质上是迭代的,并要求我们提供一组初始权重,这些权重需要随着时间的推移而更新。</p> <p>初始重量在决定训练的最终结果方面起着巨大的作用。权重的错误初始化会导致渐变消失或爆炸,这显然是不希望的。因此,我们使用一些标准的方法来初始化这些层,这将在本文中讨论。</p> <h2 id="一般的经验法则">一般的经验法则</h2> <p>一个经验法则是<em>“初始模型权重需要接近零,而不是零”</em>。一个天真的想法是从任意接近 0 的分布中取样。</p> <p>例如,您可以选择使用从 U(-0.01,0.01)或 N(0,0.01)中采样的值来填充权重。</p> <p>事实证明,上述想法一点也不幼稚,大多数标准方法都是基于均匀分布和正态分布的抽样。</p> <p>但是真正的技巧在于为这些分布设置边界条件。一个常用的边界条件是 1/sqrt(n),其中 n 是层的输入数。</p> <p>在 PyTorch 中,我们可以使用<code>uniform_</code>和<code>normal_</code>函数从均匀分布或<a href="https://www.askpython.com/python/normal-distribution" target="_blank">正态分布</a>中设置要采样的层的权重。这里有一个简单的<code>uniform_()</code>和<code>normal_()</code>的例子。</p> <pre><code class="language-py"># Linear Dense Layer layer_1 = nn.Linear(5, 2) print("Initial Weight of layer 1:") print(layer_1.weight) # Initialization with uniform distribution nn.init.uniform_(layer_1.weight, -1/sqrt(5), 1/sqrt(5)) print("\nWeight after sampling from Uniform Distribution:\n") print(layer_1.weight) # Initialization with normal distribution nn.init.normal_(layer_1.weight, 0, 1/sqrt(5)) print("\nWeight after sampling from Normal Distribution:\n") print(layer_1.weight) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">Initial Weight of layer 1: Parameter containing: tensor([[-0.0871, -0.0804, 0.2327, -0.1453, -0.1019], [-0.1338, -0.2465, 0.3257, -0.2669, -0.1537]], requires_grad=True) Weight after sampling from Uniform Distribution: Parameter containing: tensor([[ 0.4370, -0.4110, 0.2631, -0.3564, 0.0707], [-0.0009, 0.3716, -0.3596, 0.3667, 0.2465]], requires_grad=True) Weight after sampling from Normal Distribution: Parameter containing: tensor([[-0.2148, 0.1156, 0.7121, 0.2840, -0.4302], [-0.2647, 0.2148, -0.0852, -0.3813, 0.6983]], requires_grad=True) </code></pre> <p>但是这种方法也有一些限制。这些方法有点过于一般化,对于具有非线性激活函数的层,如<code>Sigmoid</code>、<code>Tanh</code>和<code>ReLU</code>激活,往往会有一些问题,在这些层中,消失和爆炸梯度的可能性很高。</p> <p>因此,在下一节中,我们将探讨一些已经提出的解决这个问题的高级方法。</p> <h2 id="非线性激活层的初始化">非线性激活层的初始化</h2> <p>对于具有非线性激活的层的权重初始化,有两种标准方法-Xavier(Glorot)初始化和明凯初始化。</p> <p>我们不会深究数学表达式和证明,而是更关注在哪里使用它们以及如何应用它们。这绝对不是邀请跳过数学背景。</p> <h3 id="1xavier-初始化">1.Xavier 初始化</h3> <p>Xavier 初始化用于具有<code>Sigmoid</code>和<code>Tanh</code>激活功能的层。Xavier 初始化有两个不同的版本。区别在于我们对数据进行采样的分布——均匀分布和正态分布。以下是这两种变体的简要概述:</p> <h3 id="2泽维尔均匀分布">2.<strong>泽维尔均匀分布</strong></h3> <p>在该方法中,权重张量填充有从均匀分布 U(-a,a)采样的值,其中,</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6b03bd301f3e8319e91c0b7a8a8303ce.png" alt="Sunday 18 April 2021 052906 PM IST" loading="lazy"></p> <p><code>input_dim</code>和<code>output_dim</code>是输出和输入维度,或者更明确地是前一层和前一层的维度,<code>gain</code>只是一个比例因子。</p> <p><strong>举例:</strong></p> <pre><code class="language-py"># The convolution layer conv_layer = nn.Conv2d(1, 4, (2,2)) # Initiliazing with Xavier Uniform nn.init.xavier_uniform_(conv_layer.weight) </code></pre> <h3 id="3泽维尔正态分布">3.泽维尔正态分布</h3> <p>该方法类似于前一种方法,除了数值是从正态分布<img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cf1bd7b98ddd57fd0c2257d663b92d5b.png" alt="Normal" loading="lazy">中采样的事实,其中,</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8c21b0df93e09ee55abe67d9c90823ff.png" alt="Xavier Normal" loading="lazy"></p> <p>并且<code>input_dim</code>和<code>output_dim</code>是输出和输入维度,或者更明确地是前一层和前一层的维度。</p> <p><strong>举例:</strong></p> <pre><code class="language-py"># The convolution layer conv_layer = nn.Conv2d(1, 4, (2,2)) # Initiliazing with Xavier Normal nn.init.xavier_normal_(conv_layer.weight) </code></pre> <h2 id="明凯初始化">明凯初始化</h2> <p>到目前为止,我们已经讨论了当层具有<code>sigmoid</code>和<code>Tanh</code>激活函数时如何初始化权重。我们还没有讨论过关于<code>ReLU</code>的问题。</p> <p>具有<code>ReLU</code>激活函数的层曾经使用 Xavier 方法初始化,直到明凯提出他的初始化层<code>ReLU</code>激活函数的方法。明凯与泽维尔的初始化有一点不同,只是在数学公式中加入了边界条件。</p> <p>Kaming 的 PyTorch 实现不仅处理 ReLU,还处理 LeakyReLU。PyTorch 提供了两种不同的明凯初始化模式——扇入模式和扇出模式。使用扇入模式将确保数据不会爆炸或内爆。类似地,扇出模式将试图在反向传播中保持梯度。</p> <h3 id="1明凯均匀分布">1.明凯均匀分布</h3> <p>权重张量填充有从均匀分布 U(-a,a)采样的值,其中,</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c99c41e71dce8f8c5fa9969545c5718f.png" alt="Image 5" loading="lazy"></p> <p>对于扇入模式,使用输入尺寸,而对于扇出模式,使用输出尺寸。ReLU 的增益为√2,LeakyReLu 的增益为√(1/a^2 +1)。</p> <p>增益通常由<code>kaiming_uniform_()</code>和<code>kaiming_normal_()</code>函数负责,我们只需指定要处理的非线性类型。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">conv_layer = nn.Conv2d(1, 4, (2,2)) nn.init.kaiming_uniform_(conv_layer.weight, mode='fan_in', nonlinearity='relu') </code></pre> <h3 id="2明凯正态分布">2.明凯正态分布</h3> <p>层权重从正态分布<img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cf1bd7b98ddd57fd0c2257d663b92d5b.png" alt="Normal" loading="lazy">中采样,其中,</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/20eca4469da84aa39ebdf9d6e10e0b34.png" alt="Image 6" loading="lazy"></p> <p>并且 input_dim 和 output_dim 是输出和输入尺寸,并且根据操作模式的选择来选择。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">conv_layer = nn.Conv2d(1, 4, (2,2)) nn.init.kaiming_normal_(conv_layer.weight, mode='fan_in', nonlinearity='relu') </code></pre> <h2 id="在-pytorch-模型中集成初始化规则">在 PyTorch 模型中集成初始化规则</h2> <p>现在我们已经熟悉了如何使用 PyTorch 初始化单层,我们可以尝试初始化现实生活中的 PyTorch 模型的层。我们可以在模型定义中进行这种初始化,或者在定义模型之后应用这些方法。</p> <h3 id="1定义模型时初始化">1.定义模型时初始化</h3> <pre><code class="language-py">import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): # Layer definitions super().__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) # Initialization nn.init.kaiming_normal_(self.fc1.weight, mode='fan_in', nonlinearity='relu') nn.init.kaiming_normal_(self.fc2.weight, mode='fan_in', nonlinearity='relu') nn.init.xavier_normal_(self.fc3.weight) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) x = nn.sigmoid(x) return x # Every time you create a new mode, it will have a weight initialized model net = Net() </code></pre> <h3 id="2创建模型后初始化">2.创建模型后初始化</h3> <p>您可以在创建模型后随时更改权重,您可以通过为特定类型的层定义规则并将其应用于整个模型,或者仅通过初始化单个层来实现这一点。</p> <pre><code class="language-py"># Defining a method for initialization of linear weights # The initialization will be applied to all linear layers # irrespective of their activation function def init_weights(m): if type(m) == nn.Linear: torch.nn.init.xavier_uniform(m.weight) # Applying it to our net net.apply(init_weights) </code></pre> <pre><code class="language-py"># Create the model net = Net() # Apply the Xavier normal method to the last layer nn.init.xavier_normal_(self.fc3.weight) </code></pre> <h2 id="结论-63">结论</h2> <p>这就把我们带到了本文关于权重初始化的结尾。敬请关注更多关于深度学习和 PyTorch 的此类文章。</p> <h1 id="如何在-python-中初始化字典分步指南">如何在 Python 中初始化字典——分步指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/dictionary/initialize-python-dictionary" target="_blank">https://www.askpython.com/python/dictionary/initialize-python-dictionary</a></p> </blockquote> <p>您来这里是因为您想学习如何用 Python 初始化字典。我来告诉你怎么做。</p> <hr> <h2 id="python-中的字典是什么">python 中的字典是什么?</h2> <p>在 Python 中,Dictionary 是一个无序的项集合,包含成对的键和值。我们可以通过下面的例子更好地理解。</p> <pre><code class="language-py">dictionary = { 1:"integer", 2.03:"Decimal", "Lion":"Animal"} </code></pre> <p>在上面的字典中:</p> <ul> <li>“整数”是键“1”的值</li> <li>“Decimal”是键“2.03”的值</li> <li>“动物”是“狮子”的关键值</li> </ul> <h2 id="初始化-python-字典的不同方法">初始化 Python 字典的不同方法</h2> <p>我们可以使用 python 中的不同方法来定义或初始化我们的字典,如下所示。</p> <h3 id="通过传递文字初始化字典">通过传递文字初始化字典</h3> <p>我们可以通过将键值对作为文字传递来创建字典。下面通过一个适当的例子给出了传递文字的语法。</p> <pre><code class="language-py">dictionary_name = { key1 : value1, key2 : value2, key3 : value3 } </code></pre> <pre><code class="language-py">my_dictionary = { "Lion" : "Animal", "Parrot" : "Bird", "Cobra" : "Reptile", "Human" : "Mammals" } print(my_dictionary) </code></pre> <p>我们名为“<code>my_dictionary</code>”的字典将会这样创建,</p> <pre><code class="language-py">{'Lion': 'Animal', 'Parrot': 'Bird', 'Cobra': 'Reptile', 'Human': 'Mammals'} </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5aa25505888683d8ae9040d474aea9f5.png" alt="Initializing Dictionary By Passing Literals" loading="lazy"></p> <p>Initializing Dictionary By Passing Literals</p> <h3 id="使用-dict构造函数初始化字典">使用 dict()构造函数初始化字典</h3> <p>我们可以使用 <a href="https://www.askpython.com/python/dictionary/python-dictionary-dict-tutorial" target="_blank"><code>dict</code>()构造函数</a>创建一个字典,如下所示。</p> <pre><code class="language-py">my_dictionary = dict( Lion = "Animal", Parrot = "Bird", Cobra = "Reptile", Human = 'Mammals' ) print(my_dictionary) </code></pre> <p>我们的字典将像前面的方法一样被创建。</p> <p>{ '狮子':'动物','鹦鹉':'鸟','眼镜蛇':'爬行动物','人类':'哺乳动物' }</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/4cb94860409e89a28b67ae455a43f870.png" alt="Initializing Dictionary Using Dict Constructor" loading="lazy"></p> <p>Initializing Dictionary Using <code>Dict</code>() Constructor</p> <h3 id="使用列表初始化字典">使用列表初始化字典</h3> <p>我们可以通过分别使用两个不同的键和值列表来创建字典,如下所示。</p> <p>让我们按照代码片段分别创建两个不同的键和值列表。</p> <pre><code class="language-py">Keys = ["Lion", "Parrot", "Cobra", "Human"] Values = ["Animal", "Bird", "Reptile", "Mammals"] </code></pre> <p>我们将在<code>dict</code>()构造函数中使用 <a href="https://www.askpython.com/python/list/convert-list-to-a-dictionary" target="_blank"><code>zip</code>()方法</a>,如下所示。</p> <pre><code class="language-py">my_dict = dict(zip(Keys,Values )) print(my_dict) </code></pre> <p>我们的字典将被创建如下</p> <pre><code class="language-py">{1: 'Integer', 2.0: 'Decimal', 'Lion': 'Animal', 'Parrot': 'Bird'} </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1de0576969d739917281382eaea3abfa.png" alt="Initializing Dictionary Using Lists" loading="lazy"></p> <p>Initializing Dictionary Using <code>Lists</code></p> <p><em><strong>也读:<a href="https://www.askpython.com/python/list/convert-list-to-a-dictionary" target="_blank">如何用 Python 把列表转换成字典?</a></strong></em></p> <h3 id="使用元组初始化字典">使用元组初始化字典</h3> <p>我们可以使用元组来创建字典。元组是单个变量中多个项目的集合,与数据类型无关。它可以存储一个或多个不同数据类型的值。我们可以通过使用元组来创建字典。让我们首先创建一个元组列表。</p> <pre><code class="language-py">Tuples = [(1 , "Integer"), (2.0 , "Decimal"), ("Lion" , "Animal"),("Parrot" , "Bird")] My_dict = dict(Tuples) print(My_dict) </code></pre> <p>在上面的代码片段中,<code>(1 , "Integer"), (2.0 , "Decimal"), ("Lion" , "Animal")</code> & <code>("Parrot" , "Bird")</code>都是元组。</p> <p>我们已经创建了一个名为“<code>Tuples</code>”的元组列表。我们通过在<code>dict</code>()构造函数中将<code>Tuple</code>作为参数传递来创建我们需要的<code>Dictionary</code>。我们的字典是这样创建的。</p> <pre><code class="language-py">{1: 'Integer', 2.0: 'Decimal', 'Lion': 'Animal', 'Parrot': 'Bird'} </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/37820d0ef1b26df1e1514deb26d50e4d.png" alt="Initializing Dictionary Using Tuples" loading="lazy"></p> <p>Initializing Dictionary Using Tuples</p> <h3 id="使用__setitem__-方法初始化字典">使用<code>__setitem__</code> 方法初始化字典</h3> <p>通过下面给出的代码片段,我们可以使用<code>__setitem__</code> 方法创建一个字典。首先,我们需要创建一个空字典。</p> <pre><code class="language-py">dict2 = {} </code></pre> <p>我们需要使用下面的 <strong><code>__setitem__</code></strong> 方法将<strong>键</strong>以及<strong>值</strong>输入到 <strong>dict2</strong> 中。</p> <pre><code class="language-py">dict2.__setitem__('key1', 'GEEK') dict2.__setitem__('key2', 'God') dict2.__setitem__('key3', 'is') dict2.__setitem__('key4', 'Great') print(dict2) </code></pre> <p>我们的字典将会像这样被创建,</p> <pre><code class="language-py">{'key1': 'GEEK', 'key2': 'God', 'key3': 'is', 'key4': 'Great'} </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/c5c7e6df0074bb4fdc465380b83d2370.png" alt="Initializing Dictionary Using __setitem__ Method" loading="lazy"></p> <p>Initializing Dictionary Using <code>__setitem__</code> Method</p> <h3 id="使用fromkeys方法初始化字典">使用<code>fromkeys</code>()方法初始化字典</h3> <p>我们可以使用 fromkeys()方法将一个公共值赋给字典中的某些键。</p> <p>让我们取一列键并使用<code>fromkeys</code>()方法如下:</p> <pre><code class="language-py">new_key = ["James", "Potter", "mathew"] dict3 = dict.fromkeys(new_key, "men") print(dict3) </code></pre> <p>print 函数应该打印上面代码片段的字典。</p> <pre><code class="language-py">{'James': 'men', 'Potter': 'men', 'mathew': 'men'} </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/52a23d21ffbc6dd9cadb636254996209.png" alt="Initializing Dictionary Using fromkeys () Method" loading="lazy"></p> <p>Initializing Dictionary Using <code>fromkeys</code>() Method</p> <p>除了使用<code>fromkeys</code>()方法,我们还可以为循环应用一个<a href="https://www.askpython.com/python/python-for-loop" target="_blank">来获得与上面相同的输出。</a></p> <pre><code class="language-py">dict4={} for x in new_key: dict4[x] = "Men" </code></pre> <p>我们可以买同样的字典。</p> <pre><code class="language-py">{'James': 'men', 'Potter': 'men', 'mathew': 'men'} </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/540530e9c54e4ca78f3706e5fce1f6f4.png" alt="Initializing Dictionary Using For Loop Instead Of fromkeys() Method" loading="lazy"></p> <p>Initializing Dictionary Using For Loop Instead Of <code>fromkeys</code>() Method</p> <h3 id="使用setdefault方法初始化字典">使用<code>setdefault</code>()方法初始化字典</h3> <p>我们可以使用 setdefault()方法在 python 中初始化字典,如下所示。这个方法返回一个列表理解中的键值。</p> <p>让我们创建一个名为<code>my_dictionary</code> 的空字典,并使用<code>setdefault</code>()方法为各个键指定 null 值。</p> <pre><code class="language-py">my_dictionary = {} [my_dictionary.setdefault(i, []) for i in range(4)] </code></pre> <p>同样,在我们的字典中追加各自需要的值。</p> <pre><code class="language-py">my_dictionary[0].append('George') my_dictionary[1].append('John') print(my_dictionary) </code></pre> <p>我们可以如下得到我们的字典。</p> <pre><code class="language-py">{0: ['George'], 1: ['John'], 2: [], 3: []} </code></pre> <p>再次追加一个值:</p> <pre><code class="language-py">my_dictionary[3].append('hrithik') print(my_dictionary) </code></pre> <p>同样,我们可以如下获取字典。</p> <pre><code class="language-py">{0: ['George'], 1: ['John'], 2: [], 3: ['hrithik'] } </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7b408f55e9dc9d2e34c633307c1ee266.png" alt="Initializing Dictionary Using setdefault() Method" loading="lazy"></p> <p>Initializing Dictionary Using <code>setdefault</code>() Method</p> <h3 id="初始化空字典">初始化空字典</h3> <p>我们可以按照代码片段初始化一个空字典。</p> <pre><code class="language-py">My_dict = {} </code></pre> <p>它将创建一个空字典。</p> <pre><code class="language-py">print(My_dict) {} </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/29dc0ce3919525b3859fd148396398fa.png" alt="Empty Dictionary" loading="lazy"></p> <p>Empty Dictionary</p> <h2 id="结论-64"><strong>结论</strong></h2> <p>在本文中,我们介绍了如何以不同的方式初始化 Python 字典。希望你已经练习并喜欢了我们的代码片段。我们必须带着一些更令人兴奋的话题再次访问。</p> <h1 id="numpy-数组的内积快速指南">Numpy 数组的内积——快速指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/numpy/inner-product-numpy-array" target="_blank">https://www.askpython.com/python-modules/numpy/inner-product-numpy-array</a></p> </blockquote> <p>在本文中,我们将学习如何在两个数组之间执行内积运算。我们将研究一维数组和多维数组。让我们先来看看什么是 Numpy 数组。</p> <h2 id="什么是-numpy-数组">什么是 NumPy 数组?</h2> <p>Numpy 是一个用于科学计算的开源 python 库。Numpy 数组类似于列表,除了它包含相似数据类型的对象,并且比列表快得多。</p> <p>对于科学计算,它们是 Python 中最重要的数据结构之一。numpy 数组高效、通用且易于使用。它们也是多维的,这意味着它们可以在多个维度上存储数据。维数称为数组的秩。数组可以有任何秩,但大多数数组要么有一维,要么有二维。</p> <p>让我们看看如何创建一个 Numpy 数组。</p> <pre><code class="language-py">import numpy as np a=np.array([1,2,3]) print (a) </code></pre> <p>输出</p> <pre><code class="language-py">[1 2 3] </code></pre> <h2 id="numpy-阵列上的内积">Numpy 阵列上的内积</h2> <p>我们可以借助一个简单的 numpy.inner()函数来执行数组的内积。</p> <p>语法:</p> <pre><code class="language-py">numpy.inner(arr1, arr2)=sum(array1[:] , array2[:]) </code></pre> <h2 id="一维-numpy-数组的内积">一维 Numpy 数组的内积</h2> <p>您可以对 Numpy 数组的一维内积使用以下代码。</p> <pre><code class="language-py">import numpy as np a= np.array([1,2,3]) b= np.array([0,1,0]) product=np.inner(a,b) print(product) </code></pre> <p><strong>输出</strong></p> <pre><code class="language-py">2 </code></pre> <p>这里的输出乘积等于[1<em>0+2</em>1+3*0]=2</p> <h2 id="多维数组的内积">多维数组的内积</h2> <p>您可以对多维数组使用以下代码。</p> <pre><code class="language-py">import numpy as np a = np.array([[1,3], [4,5]]) b = np.array([[11, 12], [15, 16]]) product=np.inner(a,b) print(product) </code></pre> <p>输出</p> <pre><code class="language-py">[[ 47 63] [104 140]] </code></pre> <h2 id="结论-65">结论</h2> <p>总之,我们学习了如何在 Numpy 数组上执行内积。希望这篇文章对你有用!</p> <h1 id="python-中的有序树遍历实现">Python 中的有序树遍历[实现]</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/inorder-tree-traversal" target="_blank">https://www.askpython.com/python/examples/inorder-tree-traversal</a></p> </blockquote> <p>在本文中,我们将研究有序树遍历的概念和算法。然后我们将在 python 中实现有序遍历的算法,并在一个<a href="https://www.askpython.com/python/examples/binary-search-tree" target="_blank">二叉查找树</a>上运行它。</p> <h2 id="什么是有序树遍历">什么是有序树遍历?</h2> <p>有序遍历是一种深度优先的树遍历算法。在深度优先遍历中,我们从根节点开始,然后探索树的一个分支,直到结束,然后我们回溯并遍历另一个分支。</p> <p>在有序遍历中,首先,我们遍历当前节点的左子树或左子树,然后我们遍历当前节点,然后我们遍历当前节点的右子树或右子树。我们递归地执行这个操作,直到所有的节点都被遍历。我们使用 inorder 遍历以升序打印二叉查找树的元素。</p> <h2 id="有序树遍历算法">有序树遍历算法</h2> <p>下面是有序遍历的算法。</p> <pre><code class="language-py">Algorithm inorder: Input: Reference to Root Node Output:Prints All the nodes of the tree Start. 1.If root is empty,return. 2.Traverse left subtree of the root.// inorder(root.leftChild) 3\. Traverse the root node. //print value at node 4\. Traverse the right subtree of the root.// inorder(root.rightChild) End. </code></pre> <h2 id="有序遍历算法在-python-中的实现">有序遍历算法在 Python 中的实现</h2> <p>现在,我们将实现上述算法,以在有序遍历中打印以下二叉查找树的节点。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/84488fba58a7c4dae9beaca7b846692c.png" alt="bst" loading="lazy"></p> <p>Binary Search Tree</p> <p>在下面的代码中,首先创建了上面的二叉查找树,然后输出二叉树的有序遍历。</p> <pre><code class="language-py">class BinaryTreeNode: def __init__(self, data): self.data = data self.leftChild = None self.rightChild=None def insert(root,newValue): #if binary search tree is empty, make a new node and declare it as root if root is None: root=BinaryTreeNode(newValue) return root #binary search tree is not empty, so we will insert it into the tree #if newValue is less than value of data in root, add it to left subtree and proceed recursively if newValue<root.data: root.leftChild=insert(root.leftChild,newValue) else: #if newValue is greater than value of data in root, add it to right subtree and proceed recursively root.rightChild=insert(root.rightChild,newValue) return root def inorder(root): #if root is None,return if root==None: return #traverse left subtree inorder(root.leftChild) #traverse current node print(root.data) #traverse right subtree inorder(root.rightChild) root= insert(None,15) insert(root,10) insert(root,25) insert(root,6) insert(root,14) insert(root,20) insert(root,60) print("Printing values of binary search tree in Inorder Traversal.") inorder(root) </code></pre> <p>输出:</p> <pre><code class="language-py">Printing values of binary search tree in Inorder Traversal. 6 10 14 15 20 25 60 </code></pre> <p>在这里,我们可以看到值是以递增的顺序打印的。因此,如果要求您按升序打印二叉查找树中的数据,您只需对二叉查找树执行一次有序遍历。</p> <h2 id="结论-66">结论</h2> <p>在本文中,我们学习了有序树遍历的概念。我们还研究了该算法,并用 python 实现了该算法来遍历二叉查找树,并发现对于二叉查找树,按顺序遍历会按升序打印值。请继续关注更多内容丰富的文章。</p> <p>快乐学习!</p> <h1 id="在-python-中-inplace--true-是什么意思">在 Python 中 inplace = True 是什么意思?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/pandas/inplace-true-parameter" target="_blank">https://www.askpython.com/python-modules/pandas/inplace-true-parameter</a></p> </blockquote> <p>当开始使用 <a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">pandas</a> 甚至在网站上查询 pandas 操作时,我们经常会遇到代码中出现的<strong>就地</strong>参数。<strong>原地的默认值设置为假。</strong></p> <p>在本文中,我们将探讨在数据帧上执行操作时,inplace 参数的作用。</p> <h2 id="inplace-参数有什么作用">inplace 参数有什么作用?</h2> <p><code>inplace=True</code> 的使用取决于我们是否要对原始 df 进行修改。</p> <p>让我们考虑删除已删除 NA 条目的行的操作。我们有一个数据框架(df)。</p> <pre><code class="language-py">df.dropna(axis='index', how='all', inplace=True) </code></pre> <p>在熊猫中,上述代码的意思是:</p> <ol> <li>熊猫创建原始数据的副本。</li> <li>对其执行所需的操作。</li> <li>将结果分配给原始数据。(这里要考虑的重要一点)。</li> <li>然后删除副本。</li> </ol> <p>上面的代码什么也不返回,只是修改了原始的<a href="https://www.askpython.com/python-modules/pandas/dataframes-in-python" target="_blank">数据帧</a>。</p> <p>如果 inplace 设置为<code>False</code>,那么 pandas 将返回一个数据帧的副本,并在其上执行操作。</p> <p>在 Pandas 中,我们有许多带有<code>inplace</code>参数的函数。</p> <p>因此,当我们做<code>df.dropna(axis='index', how='all', inplace=True)</code>时,pandas 知道我们想要改变原始数据帧,因此它在原始数据帧上执行所需的改变。</p> <h2 id="inplace-真实的行动">Inplace =真实的行动</h2> <p>让我们看看 inplace 参数的作用。我们将对 IRIS 数据集执行<a href="https://www.askpython.com/python/examples/quicksort-algorithm" target="_blank">排序操作</a>,以演示<code>inplace</code>参数的用途。</p> <p>点击可以了解更多关于加载虹膜数据集<a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html" target="_blank">的信息。</a></p> <pre><code class="language-py"># Importing required libraries from sklearn.datasets import load_iris import pandas as pd #Loading the dataset data = load_iris(as_frame=True) df = pd.DataFrame(data.data) df </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/4fb36eebbb8208603d8a0fa7709ebf70.png" alt="Original Dataframe" loading="lazy"></p> <p><strong>Original Dataframe</strong></p> <p>现在让我们对<code>petal length</code>特征进行排序操作</p> <pre><code class="language-py">df.sort_values('petal length (cm)' , ascending = True) #inplace by default set to False </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/21aaaaf5f720cdd69c62f424a1e7a6ad.png" alt="Output After Sorting" loading="lazy"></p> <p>Output After Sorting</p> <p>现在让我们检查一下我们的原始数据帧发生了什么。</p> <pre><code class="language-py">df </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/228606f5ce7b5cf69a79202e2b8cfb0c.png" alt="Original Dataframe When Inplace Was At Its Default Value" loading="lazy"></p> <p>Original Dataframe When Inplace Was At Its Default Value</p> <p><em><strong>我们只是在打印时得到了原始数据帧,即使我们对它进行了排序操作。</strong></em></p> <p>那么…刚刚发生了什么?</p> <p>上面的例子很好地演示了 inplace 参数的应用。</p> <p>默认情况下,它被设置为 False,因此该操作不会修改原始数据帧。相反,它返回一个对其执行操作的副本。</p> <p>在上面的代码中,我们没有将返回的数据帧赋给任何新的变量,我们没有得到一个已排序的新数据帧。</p> <pre><code class="language-py">new_df = df.sort_values('petal length (cm)' , ascending = True , inplace=False) new_df </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f2dc57321804c2d85244a8f3780281bf.png" alt="Sorted New Dataframe When Inplace Is Set To False" loading="lazy"></p> <p>Sorted New Dataframe When Inplace Is Set To False</p> <p>我们只是将返回的数据帧赋给一个名为 new_df 的变量。</p> <p>现在,它是原始数据帧的排序副本。</p> <p>这里要考虑的重要一点是,原始数据帧仍然是相同的,并且确实经历了我们指定的任何转换。</p> <p>现在让我们看看如果我们设置<code>inplace = True</code>会发生什么</p> <pre><code class="language-py">df.sort_values('petal length (cm)' , ascending = True , inplace = True) </code></pre> <p>运行代码似乎没有返回任何输出。但是等等..!</p> <p>在检查了原始数据帧之后,我们得到了<code>inplace = True</code>正在做的事情的本质。</p> <pre><code class="language-py">df </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/d42a9a11c5df20e4a67526f864d0b229.png" alt="Output When Inplace Is Set To True" loading="lazy"></p> <p>Output When Inplace Is Set To True</p> <p>在 Python 中设置了 inplace=true 之后,原始数据帧被修改了。</p> <h2 id="结论-67">结论</h2> <p>这篇文章是关于就地参数的。我们现在对这个隐藏的参数有了一定的了解,它经常出现在函数中,而我们甚至没有意识到。</p> <p>最后,我们在使用 inplace=True 时应该非常小心,因为它会修改原始数据框。</p> <p>快乐学习!</p> <h1 id="如何在-sqlite3-数据库中插入多条记录">如何在 Sqlite3 数据库中插入多条记录</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/insert-multiple-records-sqlite3" target="_blank">https://www.askpython.com/python/examples/insert-multiple-records-sqlite3</a></p> </blockquote> <p>大家好,在本文中,我们将学习 Sqlite3 数据库如何工作,以及如何使用 Python 一次添加多行。现在,数据库基于四种基本操作 CRUD。</p> <ol> <li>创造</li> <li>恢复</li> <li>更新</li> <li>删除</li> </ol> <p>当今技术领域中最常用的数据库类型是关系数据库。它们的名字本身就定义了它们的功能——用一些特殊的键连接起来的桌子。其中之一是 Sqlite3 数据库。</p> <h2 id="sql-与-sqlite3">SQL 与 SQLite3</h2> <p>让我们快速比较一下 SQL 和 SQLite 有什么相似和不同之处。</p> <h3 id="什么是-sql">什么是 SQL?</h3> <p>SQL 是一种帮助我们与数据库交流的语言。SQL 的命令被专门称为“查询”。每个查询都有一个特殊的目的。这种解释语言没有任何特殊的编译器,而是从特殊的 SQL 框架中执行它。互联网上有各种各样的服务器。其中一个就是 SQLite3。</p> <h3 id="什么是-sqlite3">什么是 SQLite3?</h3> <p>SQLite3 框架是一个轻量级的 SQL 服务器。以下是 SQLite3 的一些特性。</p> <ol> <li>原始工作不需要服务器连接。</li> <li>需要更少的内存空间。</li> <li>不需要安装,解压 zip 文件,就可以使用了。</li> <li>命令更容易执行。</li> <li>跨平台——在 Windows、Linux 和 Mac 系统上运行。</li> <li>集成–可以使用 C/C++、Java、Python 等语言进行操作。</li> </ol> <h2 id="在-sqlite3-数据库中插入多条记录的步骤">在 Sqlite3 数据库中插入多条记录的步骤</h2> <p>本文的这一部分告诉我们如何将 SQLite3 与 Python 结合使用,并在 SQL 的一个命令中添加多个记录。</p> <p><strong>注意:<a href="#5-adding-multiple-records-at-a-time">对于使用 Python 在 SQLite3 数据库中添加多条记录的代码,跳到第 5 点</a></strong> 。</p> <h3 id="1设置环境">1.设置环境</h3> <p>当我们使用任何数据库时,我们需要设置一些点。在处理大型项目时,这是一个很好的实践。</p> <ol> <li>创建一个文件夹 SQLITE 来保存我们所有的数据库和代码。</li> <li>在该文件夹中创建另一个文件夹作为数据库。这将包含所有的数据库。</li> <li>从官网:<a href="https://sqlite.org/download.html" target="_blank">https://sqlite.org/download.html</a>下载 slqite3 压缩包,搜索预编译的 Windows 二进制文件。我们可以根据我们的系统选择它是 32 位还是 64 位。</li> <li>下载完成后,将 zip 文件解压到我们的 SQLite 文件夹中。这就行了,不需要安装任何东西。</li> <li>创建一个 python 文件 data.py,其中包含我们将要编写的全部代码。</li> </ol> <p><strong>现在看起来会是这样:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/91dff814f09b063702acb512a7ac95aa.png" alt="Folderr Setup" loading="lazy"></p> <p>Folder Setup</p> <h3 id="2使用-python-在-sqlite3-中创建数据库">2.使用 Python 在 SQLite3 中创建数据库</h3> <p>Python 提供了一个特殊的库,名为 <strong>sqlite3</strong> ,它是一个内置的包。这样,我们的任务就变得容易了。我们只需要在我们的系统中安装 Python 3.x.x 版本。建议使用 3.6.x 版本进行无错误编程。</p> <p><strong>代码:</strong></p> <pre><code class="language-py">import sqlite3 connection = sqlite3.connect('databases/student.db') # file path # create a cursor object from the cursor class cur = connection.cursor() cur.execute(''' CREATE TABLE customers( first_name text, last_name text, email text )''') # committing our connection connection.commit() # close our connection connection.close() </code></pre> <p><strong>SQLITE 中的数据类型</strong>:SQLITE 3 中有五种数据类型</p> <ol> <li>空</li> <li>整数</li> <li>实数:小数点数字</li> <li>文本:字符串</li> <li>Blob:图像、mp3 文件、视频文件等。</li> </ol> <p><strong>说明:</strong></p> <ol> <li>导入 sqlite3 模块。</li> <li>使用 connect()方法创建一个连接对象。这个方法创建一个数据库。使用连接对象存储它。</li> <li>使用 cursor()函数创建一个游标对象。为简单的工作流程创建一个简单的对象。游标对象有助于连接到新的或现有的数据库,并对其执行操作。</li> <li>然后使用同一个游标对象调用 execute()函数。这个函数以字符串参数的形式接受所有的 SQL 查询。</li> <li>创建一个简单的数据库,保存三条记录“名字”、“姓氏”和“电子邮件”。使用 Commit()函数提交操作。使用点“.”通过连接对象调用它接线员。</li> <li>使用 Close()方法关闭连接。</li> </ol> <p>该命令还将一个“student.db”文件插入数据库文件夹。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/ca776684b3f427203095a867fe80cd0d.png" alt="Student Database Created In The Database Folder" loading="lazy"></p> <p>Student Database Created In The Database Folder</p> <h3 id="3在-sqlite-studio-中查看数据库">3.在 SQLite studio 中查看数据库</h3> <p>从解压后的 zip 文件夹中打开 SQLite studio,选择语言为<strong>“美式英语”</strong>。然后,它会打开这样一个界面:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/8dfd10c9ff025cff9884e8918d19db5e.png" alt="SQLite Studio Interface" loading="lazy"></p> <p>SQLite Studio Interface</p> <p>点击<strong>数据库</strong>栏,从中选择<strong>添加数据库</strong>选项。我们也可以使用<strong>“Ctrl+O”</strong>命令来执行。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/88446e21cbd4ce68f4aab71f80622e48.png" alt="Adding A Database 1" loading="lazy"></p> <p>Adding A Database</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7ebd0834409ff4e662e736643b819a6f.png" alt="Adding It From The System Folder" loading="lazy"></p> <p>To add the database from the system click on the folder icon</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fa0d7f63821474661aac43131a2fca26.png" alt="Select The Newly Created Student Db Database From The Database Folder" loading="lazy"></p> <p>Select the appropriate database from the folder</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1b0cbc1adc85151715177997da9d5378.png" alt="View Of The Added Database" loading="lazy"></p> <p>View of the added database</p> <h3 id="4将值插入数据库">4.将值插入数据库</h3> <p>这是最重要的查询之一。因为创建一个表并让它空着没有任何好处。因此,我们将在表中插入一些样本数据。SQLite 模块的两个方法为我们提供了同样的帮助。</p> <ol> <li><strong>execute()–一次只插入一条记录</strong>。</li> <li>execute many()–一次插入多条记录。</li> </ol> <h4 id="一次添加一条记录">一次添加一条记录</h4> <p><strong>代码:</strong></p> <pre><code class="language-py">import sqlite3 connection = sqlite3.connect('databases/student.db') # file path # create a cursor object from the cursor class cur = connection.cursor() cur.execute("INSERT INTO student_data VALUES ('Shree', 'Narayan', '[email protected]')") # committing our connection print('Command executed successfully!!!') connection.commit() # close our connection connection.close() </code></pre> <p><strong>输出:</strong></p> <p>要查看数据库中的更改,只需打开 Sqlite3 studio 并查看 studio 的<strong>数据</strong>选项。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/de4e110f891edd91fe6c7f708845a819.png" alt="Checking The Inserted Data" loading="lazy"></p> <p>Checking the inserted data</p> <p><strong>说明:</strong></p> <ol> <li>首先,连接数据库。</li> <li>然后创建一个光标对象。</li> <li>然后使用 execute()函数添加具有 <strong>name = "Shree ",last_name = "Narayan "和 email = "<a href="/cdn-cgi/l/email-protection" target="_blank">【email protected】</a>"</strong>的学生记录。</li> <li>提交更改,然后关闭连接。</li> </ol> <h3 id="5一次添加多条记录">5.一次添加多条记录</h3> <p><strong>代码:</strong></p> <pre><code class="language-py">import sqlite3 # connection = sqlite3.connect(':memeory:') connection = sqlite3.connect('databases/student.db') # file path # create a cursor object from the cursor class cur = connection.cursor() # creating a list of items multiple_columns = [('Walt', 'Diseny', '[email protected]'), ('Ben', 'Parker', '[email protected]'), ('Charlemagne', 'Butler', '[email protected]')] cur.executemany("INSERT INTO student_data VALUES (?,?,?)", multiple_columns) # committing our connection print('Command executed successfully!!!') connection.commit() # close our connection connection.close() </code></pre> <p><strong>说明:</strong></p> <ol> <li>首先,连接数据库。</li> <li>然后创建一个光标对象。</li> <li>我们需要创建一个包含三个学生数据的元组列表。将其命名为<strong>多记录</strong>。</li> <li>使用光标对象,我们将使用 <strong>executemany()</strong> 函数。使用(插入到 student_data 列值(?, ?, ?),multiple_records)命令。</li> <li>这里(?, ?, ?)是一个带有问号的<strong>占位符</strong>,问号根据特定表格的列数使用。我们有三列,所以我们使用三个占位符。</li> </ol> <p><strong>execute many()函数的语法:</strong></p> <pre><code class="language-py">cursor_object.executemany("INSERT INTO database_name VALUES (?,?,?,...?)", column_list) </code></pre> <p><strong>输出:</strong></p> <p>转到工作室,然后点击<strong>刷新按钮或按 F5,</strong>我们得到更新后的 student_data。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7123fb01c01495e055b2c33240d99976.png" alt="Inserted Multiple Records At Once" loading="lazy"></p> <p>Inserted multiple records at a time</p> <h2 id="结论-68">结论</h2> <p>在这里,我们总结了这篇文章,我希望这有助于每个人在各自的 DBMS 中进行所有可能的更改。SQLite with Python 很容易学习,但是要对每段代码进行修改。</p> <h1 id="python-中的插入排序">Python 中的插入排序</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/insertion-sort-in-python" target="_blank">https://www.askpython.com/python/examples/insertion-sort-in-python</a></p> </blockquote> <p>在本教程中,我们将学习 Python 中的插入排序,这是一种排序算法,与我们在现实生活中排序的方式非常相似。让我们开始吧。</p> <h2 id="插入排序算法">插入排序算法</h2> <p>如果你有一套从 1 到 10 的混洗卡片,并要求你对它们进行分类,你可能会一张一张地捡起每张卡片,并把它们按正确的位置插入另一个分类堆中。</p> <p>与我们倾向于对事物进行排序的方式非常相似,插入排序在给定的序列中维护一个已排序的部分,从未排序的部分中取出一个项目,然后<em>将</em>插入到已排序部分的正确位置。</p> <p>开始时,排序部分中只有一个元素,也就是第一个元素(排序部分位于列表的开头)。</p> <p>我们使用索引跟踪未排序部分的开始位置,未排序部分从第二个元素开始,因此索引需要为 1(在 Python 的情况下)。</p> <p>现在,我们从未排序的部分中取出第一个元素(未排序索引处的元素),并尝试在已排序的部分中找到它的位置。</p> <p>我们通过连续地将它与排序部分中的每个元素进行比较,直到我们找到比新元素更小(如果列表是升序)或更大(如果列表是降序)的元素。</p> <p>接下来,我们将它插入到这个位置,并将所有已排序的元素移动一次,以容纳新元素。重复该过程,直到整个<a href="https://www.askpython.com/python/array/python-array-declaration" target="_blank">数组</a>被排序。</p> <h2 id="python-中的插入排序-1">Python 中的插入排序</h2> <p>Python 中的算法如下所示:</p> <pre><code class="language-py">def insertion_sort(lst): for i in range(1, len(lst)): for j in range(i - 1, -1, -1): if(lst[j] > lst[j + 1]): lst[j], lst[j + 1] = lst[j + 1], lst[j] </code></pre> <p>请注意,该函数接收一个列表并就地执行排序。然而,改变算法返回一个排序列表是相当简单的。</p> <h3 id="了解插入排序算法">了解插入排序算法</h3> <p>让我们试着在一个例子上运行这个算法,看看它是如何工作的。</p> <ul> <li> <p>比如说,给定的列表是:12,16,11,10,14,13。</p> </li> <li> <p>给定列表的大小:6</p> </li> <li> <p>按升序排序。</p> </li> <li> <p>现在,<code>i</code>将从 1 到 5,因此,从 16 到 13 的所有元素将被插入到它们正确的位置。</p> </li> <li> <p>在第一个循环里面,<code>j</code>会从<code>i - 1</code>到 0,所以它负责找到正确的位置。<code>j</code>会随着所选项目在列表中向后移动,试图找到正确的位置。</p> </li> <li> <p>在更里面,我们将比较在<code>j</code>的项目和被选择的项目(总是在<code>j + 1</code>),如果在<code>j</code>的项目更大,位置<code>j</code>和<code>j + 1</code>将被交换,项目将向后移动。</p> </li> <li> <p>此后<code>j</code>将减 1,确保所选项目始终在位置<code>j + 1</code>。</p> </li> <li> <p>最后,<code>j</code>处的项目将不再大于所选项目,并且所选项目将已经移动到其正确的位置,并且它将结束内部循环。</p> </li> <li> <p>外部循环现在将对下一个项目做同样的事情。</p> </li> </ul> <p>序列的变化看起来大概是这样的:<br> 12 , 16 ,11,10,14,13<br> 12, 11 ,16,10,14,13<br> 11 , 12 , 16 ,16 10 , 12 , 16 ,14<br> 1310, 11 , 12 , 16 ,14<br> 1310, 11 , 12 , 16<br> 10 , 11 , 12 , 13 , 14 , 16<br> 10 , 11 , 12 ,</p> <ul> <li>绿色的项目表示它们在排序部分中处于正确的位置。</li> <li>红色的项目在向左移动到正确位置时被排序。</li> <li>未着色的项目是列表中未排序的部分。</li> </ul> <h2 id="输出-2">输出</h2> <p>对算法运行相同的列表,将产生以下结果:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f6f3f386f8e7f9bcdc36856bcf26b23c.png" alt="Insertion Sort Example" loading="lazy"></p> <p>Insertion Sort in action</p> <h2 id="结论-69">结论</h2> <p>在本教程中,我们看到了插入排序与我们在现实生活中如何排序非常相似,我们讨论了它使用的算法,并用 Python 实现了插入排序。</p> <p>之后,我们讨论了该算法是如何工作的,并在一个未排序的例子上运行了该算法。最后,我们使用代码的实际输出来验证模拟运行。插入排序和<a href="https://www.askpython.com/python/examples/bubble-sort-in-python" target="_blank">冒泡排序</a>一样,复杂度也是 O(n² )。</p> <p>与此类似,如果输入大小增加一倍,执行时间增加四倍,如果输入增加三倍,执行时间增加九倍。</p> <p>这使得该算法在实际应用中效率很低,但它是一种非常直观的算法。</p> <p>我希望你喜欢学习插入排序,下一课再见。</p> <h1 id="为什么您应该在工作流程中集成连续分析">为什么您应该在工作流程中集成连续分析</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/integrate-continuous-profiling-in-workflow" target="_blank">https://www.askpython.com/python/integrate-continuous-profiling-in-workflow</a></p> </blockquote> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/729b278acac8389086f620d7b43dfbe0.png" alt="Python Profiling" loading="lazy"></p> <p>Photo by <a href="https://unsplash.com/@firmbee?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank">Firmbee.com</a> on <a href="https://unsplash.com/s/photos/web-design?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank">Unsplash</a></p> <p>您已经编写了在开发中有效的精致代码。是时候将它投入生产供不同的人使用了。这时,成千上万的问题开始涌入你的脑海:如果 web 应用程序在生产过程中崩溃了怎么办?我如何知道我的 web 应用程序是否处于最佳性能?有没有一种技术可以让我轻松理解生产绩效?我的团队有办法解决可能导致真正生产问题的缺陷吗?</p> <p>本文将回答这些问题,并教您一个将应用程序转移到生产环境的过程。</p> <h2 id="什么是连续剖析">什么是连续剖析?</h2> <p><a href="https://granulate.io/introduction-to-continuous-profiling/" target="_blank">持续剖析</a>是在任何时间、任何规模上优化您的代码在生产中的性能的过程。它包括从生产环境中持续收集性能数据,并将其提供给开发人员和运营团队进行快速和深入的分析。</p> <p>这是一个草图,显示了持续的分析反馈。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6de916bcbf011980eec2416183dc4fa2.png" alt="Continuous Profiling Feedback" loading="lazy"></p> <h2 id="为什么要使用持续剖析">为什么要使用持续剖析?</h2> <p>您需要一个持续的概要分析架构,以便程序员可以获得关于他们代码性能的行级反馈。当我在这里说性能时,我的意思是你将看到一些有限的资源的利息消耗率。资源可以是<a href="https://whatis.techtarget.com/definition/wall-time-real-world-time-or-wall-clock-time" target="_blank">挂钟时间</a>,内存,CPU 时间,磁盘 I/O 等等。</p> <p>如果这些资源耗尽,会导致系统内的瓶颈。因此,如果您能够识别并改进利用这些资源的代码库部分,您将很快从性能衰退中恢复过来;降低成本;并改善可伸缩性、程序员的思维模式和用户体验。</p> <p>尽管您觉得需要为每种编码语言实现连续的分析器,但是概念并没有太大的不同。连续分析器无计划地定期获取概要文件,以确保开销不明显。</p> <p>分析器通过帮助像您这样的开发人员以低廉的成本解决性能问题,并自动使用为您提供有关应用程序生产行为的重要数据的分析报告,提供了惊人的好处。这些信息允许您理解和分析对您来说是热点的重要代码区域。</p> <h2 id="我们拥有的连续轮廓仪的类型">我们拥有的连续轮廓仪的类型</h2> <p>有两种主要类型的代码分析器:采样分析器和检测分析器。</p> <p><strong>1。采样分析器:</strong>也称为统计分析器,它们通过获取各种时间点的样本来估计应用程序中“花费的时间”分配。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cd26916bf8123dfaab672dff1ccf1c35.png" alt="Sampling Profilers" loading="lazy"></p> <p><a href="https://www.slideshare.net/RichardWarburton/jvm-profiling-under-the-hood" target="_blank">Source</a></p> <p><strong>2。检测分析器:</strong>它们通过升级应用程序代码和向函数中插入调用来工作,这些函数计算进程被调用的次数和在函数中花费的时间。与这种性能分析相关的开销通常很高,因为探查器直接将检测注入到应用程序代码中。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/bfccc26e2c5194452846679e9a6cb295.png" alt="Instrumenting Profilers" loading="lazy"></p> <p><a href="https://www.slideshare.net/RichardWarburton/production-profiling-what-why-and-how" target="_blank">Source</a></p> <h2 id="您应该了解的连续分析器">您应该了解的连续分析器</h2> <h4 id="gprofiler">Gprofiler</h4> <p>gProfiler 是一个开源的连续分析器,你可以用最少的努力无缝地安装它,不需要修改代码:它是即插即用的。产品代码的可见性立即得到了促进,gProfiler 被配置为在后台持续工作。</p> <p>因此,以最少的 CPU 使用量实时分析性能问题变得更加容易。它还致力于优化应用程序的云使用,使其成为一个经济高效的解决方案。</p> <p>它支持 Python、Java、Go、Scala、Clojure 和 Kotlin 应用程序等编程语言。</p> <h4 id="datadog-连续剖面仪"><strong>Datadog 连续剖面仪</strong></h4> <p>Datadog 的<a href="https://www.datadoghq.com/product/code-profiling/" target="_blank">连续分析器</a>可以轻松发现占用更多 CPU 或内存的代码行。它配备了运行在主机应用程序上的 Datadog 代理。它可以支持用不同的编码语言编写的应用程序,如 Python、Java 和 Go,但是您获得的概要信息类型会因语言而异。</p> <p>例如,Java 应用程序是唯一一个为您提供每个方法读写文件所用时间的分析信息的应用程序。但是,CPU 中使用的每个函数的时间在所有编程语言中都是可以访问的。</p> <h4 id="亚马逊-codeguru-profiler"><strong>亚马逊 CodeGuru Profiler</strong></h4> <p><a href="https://aws.amazon.com/codeguru/" target="_blank">Amazon CodeGuru Profiler</a> 帮助程序员理解应用程序的行为运行时,并找到代价高昂的代码行。您可以利用它来诊断性能问题,如<a href="https://www.cloudflare.com/learning/performance/glossary/what-is-latency/" target="_blank">高延迟</a>或通过寻找机会提高 CPU 和内存使用率来降低吞吐量。它帮助你削减成本。</p> <p>因此,它可以在生产中不断运行,以发现性能问题,并提供机器学习支持的建议,说明如何了解和优化代码应用程序中成本最高或资源密集型的行。亚马逊 CodeGuru 支持 Java 和 Python 应用。</p> <h4 id="dynatrace-代码分析器"><strong>Dynatrace 代码分析器</strong></h4> <p><a href="https://www.dynatrace.com/technologies/net-monitoring/net-profiler/" target="_blank">Dynatrace Code Profiler</a> 使用他们获得专利的 PurePath 技术,该技术基于跨越端到端事务的代码级跟踪。它提供了 CPU 和内存工具的概要分析,允许开发人员深入到方法级别来检测问题。它支持 PHP、Java、.NET,Node.js,还有 Go。</p> <p>我们可以看到,连续概要分析器是应用程序生产中不可或缺的一部分,我希望这篇文章能够回答您关于连续概要分析的许多问题。非常感谢您的阅读。</p> <h1 id="为初学者集成-gsheets-和-python">为初学者集成 GSheets 和 Python</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/integrating-gsheets-with-python-beginners" target="_blank">https://www.askpython.com/python/examples/integrating-gsheets-with-python-beginners</a></p> </blockquote> <p>在本文中,我们将通过一个简单的循序渐进的教程来学习如何将 GSheets 与 Python 集成在一起。</p> <h2 id="介绍">介绍</h2> <p>很多时候,当我们处理代码时,我们最终会意识到我们需要一个地方来存储代码产生的信息或代码使用的信息。</p> <p>最终,在进一步观察后,我们意识到全球使用的解决方案是一种被称为<strong>数据库</strong>的东西。</p> <p>您也逐渐发现可以通过您的代码访问这些数据库,欣喜若狂之余,您迫不及待地想尝试一下。</p> <p>几周后,你意识到数据库有很多选择,你一直使用的 Google Sheets 也可以充当数据库。</p> <p>具有创建、读取、更新和删除的所有操作,或缩写为 <strong>CRUD</strong> 。</p> <p>好消息是,你是对的!</p> <p>Google Sheets 是一款允许我们在线查看、编辑和协作记录日常生活中使用的记录的软件。</p> <p>但是,有一点很多人都没有意识到。Google 还为我们提供了从代码中轻松访问工作表的功能。</p> <p>通过我们的代码,我们可以在浏览器中执行所有我们可以执行的操作!</p> <p>然而,像往常一样,为了理解代码如何工作,需要开始一步。</p> <p>所以,现在你知道接下来会发生什么了,让我们开始使用 Google Sheets 吧!</p> <h2 id="安装-google-python-客户端-api">安装 Google Python 客户端 API</h2> <p>为了开始通过 Python 使用 Google Sheets,我们首先需要确保我们有运行它的功能和能力。</p> <p>也就是说,下面是<strong>谷歌客户端库</strong>的<code>pip</code>安装命令,</p> <pre><code class="language-py">pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib </code></pre> <p>我们将使用其他几个模块,这些模块使处理记录变得更容易,这是直接使用 Google Sheets 的一种迂回方式,</p> <pre><code class="language-py">pip install gspread oauth2client </code></pre> <p>这应该适用于 Python 的大多数实例,但是,如果您似乎有任何问题,您可能希望查看<a href="https://github.com/googleapis/google-api-python-client" target="_blank">安装页面</a>。</p> <h2 id="将-gsheets-与-python-集成的步骤">将 GSheets 与 Python 集成的步骤</h2> <p>接下来,我们将看看将 GSheets 与 Python 集成的步骤。请遵循以下步骤:</p> <h3 id="1在-gcp-建立一个项目">1.在 GCP 建立一个项目</h3> <p>为了使用 GSheets API,我们首先需要创建并使用我们在<strong>谷歌云平台</strong>中创建的项目,也称为 <strong>GCP</strong> 。</p> <p>根据定义,<strong>谷歌云平台</strong>是一套云计算服务,为了与基于云的 API 进行交互,我们需要与 <strong>GCP</strong> 合作作为先决条件。</p> <p>所以,一定要记住 <strong>GCP</strong> ,和你的<strong>谷歌驱动</strong>是链接的,这意味着如果你创建一个项目,并且只启用<strong>驱动 API</strong> ,我们将能够接收 API 与脚本交互和检索数据所需的凭证。</p> <p>所以,重要的事情先来!我们必须登录各自的账户,进入<a href="https://console.cloud.google.com" target="_blank">谷歌云控制台</a>。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/d4146a1a4bda48c7cfacbcc702a8bec6.png" alt="Gcp Account" loading="lazy"></p> <p>A bit overwhelming, but, it gets easier when you look at it a bit closer.</p> <p>现在,让我们创建一个项目。方法是简单地点击<strong>选择图中红色箭头指示的项目</strong>,并在弹出窗口时创建一个<strong>新项目</strong>。</p> <p>您可以选择将任何名称作为您的项目标题,如果您不将此项目连接到特定组织,请选择“无组织”选项。</p> <p>如果您还没有重定向到仪表板,您可以通过侧栏<strong>(主页- >仪表板)</strong>访问它。</p> <h3 id="2启用驱动器-api">2.启用驱动器 API</h3> <p>现在我们已经创建了项目,是时候引入 API 了。</p> <p>寻找 API 的一个简单的解决方案是使用顶部的搜索栏,查询 <strong>Google Drive API</strong> 。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cc927b31f36cf8192249ddacabe1052d.png" alt="Gcp Bar" loading="lazy"></p> <p>Search bar located next to the selected project</p> <p>如果你找到了正确的,它应该看起来像这样,</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/14fb8c5310bb9b30fdfa50ecd19e65f5.png" alt="Gcp Drive Connect" loading="lazy"></p> <p>The Google Drive API allows for access to the Google Drive of the particular account</p> <p>现在我们在这里,让我们启用它,这应该会自动导致该 API 的概述页面。</p> <p>接下来,您需要通过侧栏进入凭证部分。<br> <strong>概述- >凭证</strong>。</p> <p>让我们根据我们的项目生成凭证,这意味着我们的响应必须符合, <strong>Google Drive API</strong> 、 <strong>Web 服务器</strong>、<strong>应用程序数据、</strong>以及对计算引擎集成的<strong>否,看起来像这样,</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/90ac227c710593b156d06505b4930dea.png" alt="Gcp Creds" loading="lazy"></p> <p>Credentials Generation Selection</p> <p>然后,我们用我们输入的<strong>服务帐户名称</strong>创建一个服务帐户,它可以是任何名称,角色为编辑。</p> <p>我们将我们的权限分配给一个编辑器,因为这允许我们执行所有的 CRUD 操作,但是不允许我们删除整个文件本身。</p> <p>我们还希望这个文件是一个 <strong>JSON</strong> 文件,正如我们将在这个例子中使用的。</p> <p>然后,我们还以类似的方式启用 <strong>Sheets API</strong> ,但是不创建任何凭证。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5e794aacf4e2e3a0bb9c4c3de9dc1aef.png" alt="Gcp Sheets Connect" loading="lazy"></p> <p>Enabling the Sheets API in a similar fashion</p> <h3 id="3使用-credsjson">3.使用 creds.json</h3> <p>现在,您可能想要返回到您已经下载的<code>JSON</code>格式的凭证,并将它存储在我们将要创建脚本的目录中。</p> <p>在这个项目中,我们将把凭证文件重命名为<code>creds.json</code>,但是,请记住,您可以对其进行重命名,但是,无论何时提到或使用该文件,都需要对其进行重命名。</p> <p>现在,在<code>creds.json</code>中,我们将收到一堆键和值,但是,我们只需要担心<code>client_email</code>键。复制这个键的值,因为我们需要用这个电子邮件 ID 来共享我们的 Google 表单,以便访问它的内容。</p> <p>接下来,要么创建一个新的工作表,要么使用现有的工作表,并通过页面右上角的共享选项添加电子邮件。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/36768279f27ef9d6b98a70647ae33719.png" alt="Sheets Bar" loading="lazy"></p> <p>Add the email to the collaborators of the spreadsheet</p> <p>在这一步结束时,您应该会得到类似这样的结果。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3f06ead4144c390387448494e99b8d27.png" alt="Sheets Accounts 1" loading="lazy"></p> <p>The gservice account requires the editor permission to be able to edit the file.</p> <p>这使得 Google 服务帐户能够访问和修改您提供的表单。</p> <h3 id="4用-python-访问-gsheets">4.用 Python 访问 Gsheets</h3> <p>终于!</p> <p>我们现在到达了实际开始编写代码的部分。</p> <p>因此,回到文章开头,我们安装了一些额外的模块,现在是我们开始使用它们的时候了。</p> <p><code>gspread</code>模块本质上是 Google Sheets 模块的 Python API,由一个像样的<a href="https://docs.gspread.org/en/latest/" target="_blank">文档</a>组成,而<code>oauth2client</code>模块只是一个与 OAuth 一起工作的库。</p> <p>oauth2client 库现在被认为是不推荐使用的,并且已经这样做了以支持 <a href="https://google-auth.readthedocs.io/en/latest/" target="_blank">google-auth</a> 库。</p> <p>然而,它将满足我们的工作与表的例子。让我们首先导入模块,开始编写脚本!</p> <pre><code class="language-py"># Authentication and access modules import gspread from oauth2client.service_account import ServiceAccountCredentials # pprint is used for pretty printing the output # It is not vital to the script in any way, but rather for us # to view the examples from pprint import pprint </code></pre> <p>接下来,我们添加访问工作表的范围,</p> <pre><code class="language-py"># sheet access scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"] </code></pre> <p>这定义了我们从中检索电子表格的页面。一旦我们完成了这些,脚本将知道在哪里寻找我们的文档,因此有了术语<code>scope</code>。</p> <p>接下来,我们继续使用<code>oauth2client</code>模块为服务帐户提供和授权我们的凭证。</p> <pre><code class="language-py">creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope) client = gspread.authorize(creds) </code></pre> <p>现在,我已经创建的工作表被命名为 <strong>tester</strong> ,并且我正在使用第一个工作表中的记录,因此,将特定的工作表分配给一个变量是以这样的方式完成的,</p> <pre><code class="language-py">sheet = client.open("tester").sheet1 </code></pre> <p>我们结束了!</p> <p>现在,我们已经建立了到工作表的连接,剩下的代码是测试电子表格的功能。</p> <p>建议您在自己的工作表/示例中进行测试,因为这是一次非常实用的体验。</p> <pre><code class="language-py"># retrieves all records print("Retrieving all records.... ") data = sheet.get_all_records() pprint(data) # retrieving specific row values print("\nRetrieving information from row 3... ") row = sheet.row_values(3) pprint(row) # retrieving specific column values print("\nRetrieving information from column 3... ") col = sheet.col_values(3) pprint(col) # retrieving specific cell print("\nRetrieving value of a cell placed at (1, 2) in the sheet... ") cell = sheet.cell(1, 2).value pprint(cell) # inserting details into the sheet print("\nInserting details into the sheet... ") insertDetails = ["Adithya", "[email protected]", "33YEP4554"] sheet.insert_row(insertDetails, 1) # updating details in the sheet print("\nUpdating details in the sheet...") sheet.update_cell(2, 2, "[email protected]") </code></pre> <p>最后,我们通过<code>sheet.insert_row</code>向工作表中插入一个值,并指定它是第 1 行的一部分。</p> <p>这是命令行的输出,</p> <pre><code class="language-py">[{'33YEP4554': 2222333312, 'Adithya': 'Murthy', '[email protected]': '[email protected]'}, {'33YEP4554': 8098776633, 'Adithya': 'John', '[email protected]': '[email protected]'}, {'33YEP4554': 123456789, 'Adithya': 'Boiler', '[email protected]': '[email protected]'}, {'33YEP4554': 2524523233, 'Adithya': 'lalith', '[email protected]': '[email protected]'}, {'33YEP4554': 2654432266, 'Adithya': 'swathi', '[email protected]': '[email protected]'}, {'33YEP4554': 6666634232, 'Adithya': 'chinnu', '[email protected]': '[email protected]'}, {'33YEP4554': 6345311456, 'Adithya': 'aditya', '[email protected]': '[email protected]'}] Retrieving information from row 3... ['John', '[email protected]', '8098776633'] Retrieving information from column 3... ['33YEP4554', '2222333312', '8098776633', '123456789', '2524523233', '2654432266', '6666634232', '6345311456'] Retrieving value of a cell placed at (1, 2) in the sheet... '[email protected]' Inserting details into the sheet... Updating details in the sheet... </code></pre> <p>这是电子表格本身的图像,</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7dd246ffba088190c319a4ae78e5b49d.png" alt="Sheet View 2" loading="lazy"></p> <p>The spreadsheet at the end of the script.</p> <h3 id="5走向">5.走向</h3> <p>既然我们已经使用了 sheets 模块的基本原理,那么在某种程度上实现自动化将是明智的。</p> <p>几个例子是通过命令行输入出现在会场的人的出席情况,或者只是将一个文件的所有记录添加到 Google Sheet 中,对输入进行一点格式化。</p> <p>gspread 文档包含了比本文所讨论的更多的特性,从更新单元格到删除整个工作表。</p> <h2 id="结论-70">结论</h2> <p>当谈到记录细节时,使用 Python 使用 Google Sheets 打开了许多大门,可能是将其用作数据库、协作记录,甚至只是更新细节,以便非编码人员可以理解它。</p> <p>总的来说,这是一个开始使用 Google API 的好方法。</p> <p>也就是说,看看其他一些可以帮助您处理数据库和配置的模块也是一个好主意,比如 <a href="https://www.askpython.com/python-modules/sql-in-python" target="_blank">SQL</a> 、<a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">熊猫</a>和 <a href="https://www.askpython.com/python/python-dotenv-module" target="_blank">dotenv 模块</a>。</p> <p><strong>此外,在你查看这些之前,这里是我们今天开发的脚本的链接—<a href="https://gist.github.com/dat-adi/c8cc33a6209e1a9aeb8d03b5e46e6483" target="_blank">要点链接</a>。</strong></p> <h2 id="参考-11">参考</h2> <ul> <li><a href="https://developers.google.com/sheets/api/guides/concepts" target="_blank">谷歌官方文档</a></li> <li><a href="https://console.cloud.google.com/getting-started" target="_blank">谷歌控制台云主页</a></li> <li><a href="https://developers.google.com/sheets/api/quickstart/python#step_1_turn_on_the" target="_blank">表单 API</a></li> <li><a href="https://developers.google.com/sheets/api/quickstart/python#step_3_set_up_the_sample" target="_blank">谷歌的快速入门代码</a></li> <li><a href="https://gist.github.com/dat-adi/c8cc33a6209e1a9aeb8d03b5e46e6483#file-test_sheet-py" target="_blank">测试脚本</a></li> </ul> <h1 id="python-opencv-中图像的灰度变换操作">Python OpenCV 中图像的灰度变换操作</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/intensity-transformation-python-opencv" target="_blank">https://www.askpython.com/python-modules/intensity-transformation-python-opencv</a></p> </blockquote> <p>嘿伙计们!在本教程中,我们将看看如何使用 Python 编程语言来改变图像的亮度。</p> <hr> <h2 id="图像强度变换介绍">图像强度变换介绍</h2> <p>为了对比度处理或图像阈值处理,对图像进行强度修改。这些是在空间域中,这意味着它们是直接在手边的图片的像素上完成的,而不是在图像的傅立叶变换上完成的。</p> <hr> <h2 id="对图像实施强度变换操作python-opencv">对图像实施强度变换操作–Python OpenCV</h2> <p>第一步包括加载必要的模块/库,并使用 <strong>OpenCV</strong> 库的 <strong>cv2.imread</strong> 函数加载我们想要在程序中处理的图像。</p> <pre><code class="language-py">import cv2 import numpy as np from google.colab.patches import cv2_imshow img = cv2.imread('sample.jpg') cv2_imshow(img) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/83f1d2ea98eb270bd4c66db464662273.png" alt="Intensity Transformations Sample Image" loading="lazy"></p> <p>Intensity Transformations Sample Image</p> <p>接下来,我们设置一个伽马值,它将定义图像的强度,并沿伽马值进行伽马校正,以获得正确强度的图像。</p> <p>最后一步,我们使用 <strong>OpenCV</strong> 库的 <strong>cv2.imwrite</strong> 方法保存图像。</p> <pre><code class="language-py">for gamma in [0.1, 0.5, 1.2, 2.2]: gamma_corrected = np.array(255*(img / 255) ** gamma, dtype = 'uint8') cv2.imwrite('gamma_transformed_'+str(gamma)+'.jpg', gamma_corrected) </code></pre> <p>四个 gamma 值的所有输出图像显示如下。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f13505ed17d992db68dfa2889e85c722.png" alt="Gamma Transformed0 1" loading="lazy"></p> <p>Gamma Transformed0 1</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/57e0832a6b207c99cace455fd33eb828.png" alt="Gamma Transformed0 5" loading="lazy"></p> <p>Gamma Transformed0 5</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7a3a003e24aa974d808f642edd903f44.png" alt="Gamma Transformed1 2" loading="lazy"></p> <p>Gamma Transformed1 2</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fda94a0071f45317ac2c44b428bfd11a.png" alt="Gamma Transformed2 2" loading="lazy"></p> <p>Gamma Transformed2 2</p> <hr> <h2 id="结论-71"><strong>结论</strong></h2> <p>恭喜你!您刚刚学习了如何使用 Python 中的 OpenCV 库构建一个 Python 程序来修改图像的亮度。希望你喜欢它!😇</p> <p>喜欢这个教程吗?无论如何,我建议你看一下下面提到的教程:</p> <ol> <li><a href="https://www.askpython.com/python/visualizing-colors-in-images" target="_blank">使用直方图可视化图像中的颜色–Python OpenCV</a></li> <li><a href="https://www.askpython.com/python/examples/draw-shapes-using-opencv" target="_blank">使用 OpenCV 绘制形状——完整的操作指南</a></li> <li><a href="https://www.askpython.com/python/examples/sketch-using-webcam" target="_blank">使用网络摄像头和 Python OpenCV[简易指南]进行实时素描</a></li> <li><a href="https://www.askpython.com/python-modules/opencv-filter2d" target="_blank">Python OpenCV filter2D()函数——完整指南</a></li> </ol> <p>感谢您抽出时间!希望你学到了新的东西!!😄</p> <hr> <h1 id="使用插值填充-python-中缺失的条目">使用插值填充 Python 中缺失的条目</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/interpolation-to-fill-missing-entries" target="_blank">https://www.askpython.com/python/examples/interpolation-to-fill-missing-entries</a></p> </blockquote> <p>插值是 Python 中的一种技术,通过它可以估计两个已知数据点之间的未知数据点。它通常用于使用已知值填充表或数据集中缺失的值。</p> <p>插值也是一种用于图像处理的技术。扩展图像时,您可以使用相邻像素来估计新像素的像素值。</p> <p>金融分析师也使用内插法,利用过去的已知数据点来预测金融未来。</p> <p>在本教程中,我们将学习插值来填充数据集中缺失的值。</p> <p><a href="https://www.askpython.com/python-modules/pandas/dataframes-in-python" target="_blank">熊猫数据帧</a>提供了一个<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html" target="_blank">。interpolate()方法</a>,可用于填充数据中缺失的条目。</p> <p>让我们创建一些虚拟数据,看看插值是如何工作的。</p> <h2 id="对系列数据中的缺失值使用插值">对系列数据中的缺失值使用插值</h2> <p>让我们创建一个带有缺失值的<a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">熊猫</a>系列。</p> <pre><code class="language-py">import pandas as pd import numpy as np a=pd.Series([0, 1, np.nan, 3,4,5,7]) </code></pre> <h3 id="1线性内插法">1.线性内插法</h3> <p>如你所见,第二个索引的值是 <strong>nan</strong> 。使用以下代码行插入数据:</p> <pre><code class="language-py">a.interpolate() </code></pre> <p>输出结果如下。:</p> <pre><code class="language-py">0 0.0 1 1.0 2 2.0 3 3.0 4 4.0 5 5.0 6 7.0 </code></pre> <p>Pandas 提供了多种插值方法。如果没有指定,线性插值是默认方法。</p> <p>让我们在相同的数据上尝试另一种类型的插值。</p> <h3 id="2多项式插值">2.多项式插值</h3> <p>多项式插值要求您指定阶数。让我们试试 2 阶插值。</p> <pre><code class="language-py">a.interpolate(method='polynomial', order=2) </code></pre> <p>输出结果如下:</p> <pre><code class="language-py">0 0.00000 1 1.00000 2 1.99537 3 3.00000 4 4.00000 5 5.00000 6 7.00000 </code></pre> <p>如果在多项式插值中给定阶数为 1,则得到与线性插值相同的输出。这是因为一阶多项式是线性的。</p> <pre><code class="language-py">a.interpolate(method='polynomial', order=1) </code></pre> <p>输出:</p> <pre><code class="language-py">0 0.0 1 1.0 2 2.0 3 3.0 4 4.0 5 5.0 6 7.0 </code></pre> <h3 id="2通过填充进行插值">2.通过填充进行插值</h3> <p>通过填充进行插值意味着复制丢失条目之前的值。</p> <p>使用填充插值时,需要指定一个界限。该限制是该方法可以连续填充的 nan 的最大数量。</p> <p>让我们看看它在 python 中是如何工作的。</p> <pre><code class="language-py">a.interpolate(method='pad', limit=2) </code></pre> <p>我们得到的输出为:</p> <pre><code class="language-py">0 0.0 1 1.0 2 1.0 3 3.0 4 4.0 5 5.0 6 7.0 </code></pre> <p>丢失的条目被替换为与其之前的条目相同的值。</p> <p>我们将极限指定为 2,让我们看看在连续三个 nan 的情况下会发生什么。</p> <pre><code class="language-py">a=pd.Series([0, 1, np.nan, np.nan, np.nan, 3,4,5,7]) a.interpolate(method='pad', limit=2) </code></pre> <p>输出如下:</p> <pre><code class="language-py">0 0.0 1 1.0 2 1.0 3 1.0 4 NaN 5 3.0 6 4.0 7 5.0 8 7.0 </code></pre> <p>第三个 nan 没有被触动。</p> <h2 id="熊猫数据帧的插值">熊猫数据帧的插值</h2> <p>我们也可以使用插值来填充熊猫数据帧中缺失的值。</p> <p>让我们创建一个虚拟数据帧,并在其上应用插值。</p> <pre><code class="language-py">s = pd.DataFrame([(0.0, np.nan, -2.0, 2.0), (np.nan, 2.0, np.nan, 1), (2.0, 5.0, np.nan, 9.0), (np.nan, 4.0, -3.0, 16.0)], columns=list('abcd')) </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/f18aeb51b3dfddaa0dbd96b1c3d73b14.png" alt="Dataframe" loading="lazy"></p> <p>Dataframe</p> <h3 id="1熊猫数据帧的线性插值">1.熊猫数据帧的线性插值</h3> <p>要在数据帧上应用线性插值,请使用以下代码行:</p> <pre><code class="language-py">s.interpolate() </code></pre> <p>输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/d9328acf2d30adcd3d1cfbf7ea719954.png" alt="Linear interpolation" loading="lazy"></p> <p>Linear interpolation</p> <p>这里, <strong>b 列</strong>下的第一个值仍然是 nan,因为在它之前没有用于插值的已知数据点。</p> <p>您还可以插入数据帧的各个列。</p> <pre><code class="language-py">s['c'].interpolate() </code></pre> <p>输出:</p> <pre><code class="language-py">0 -2.000000 1 -2.333333 2 -2.666667 3 -3.000000 </code></pre> <h3 id="2通过填充进行插值-1">2.通过填充进行插值</h3> <p>要应用填充方法,请使用以下代码行:</p> <pre><code class="language-py">s.interpolate(method='pad', limit=2) </code></pre> <p>我们得到的输出为:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/536b3d35107c9079fa4c4de5529292f7.png" alt="Padding" loading="lazy"></p> <p>Padding</p> <h2 id="结论-72">结论</h2> <p>本教程是关于 Python 中的插值。我们主要关注使用插值来填充缺失数据。希望你和我们一起玩得开心!</p> <h1 id="selenium-中的浏览器驱动程序介绍">Selenium 中的浏览器驱动程序介绍</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/introduction-browser-drivers-selenium" target="_blank">https://www.askpython.com/python-modules/introduction-browser-drivers-selenium</a></p> </blockquote> <p>Selenium 中的驱动程序对于浏览器自动化是至关重要的,而不是必须的。Python 或任何其他编程语言中的 Selenium 库使用特定的浏览器驱动程序来控制浏览器的操作,为其添加功能,并在其中操作数据(网页)。</p> <p>与最常见的声明浏览器驱动程序的方式相反,这种方式最常见,但经常会导致不兼容问题。在 Python 代码中有多种安装、初始化 web 驱动程序的方法(不太常见)。</p> <p><em><strong>推荐阅读: <a href="https://www.askpython.com/python-modules/selenium-introduction-and-setup" target="_blank">Python 硒介绍及设置</a></strong></em></p> <h2 id="下载驱动程序">下载驱动程序</h2> <p>Selenium 中最主要的错误发生在浏览器的驱动程序版本与浏览器的版本不匹配时,这就产生了兼容性问题。因此,首先,你必须始终使用与你打算用于自动化的 Web 浏览器(Google Chrome、Mozilla Firefox、Apple Safari 或任何其他浏览器)版本相同的驱动程序。</p> <p>下载和安装 Web 驱动程序是完全安全的,因为这些驱动程序由官方浏览器公司维护并相应更新,用于测试和自动化其浏览器和网页。</p> <p>检查您打算自动化的浏览器版本,并相应地从以下参考资料中下载驱动程序:</p> <table> <thead> <tr> <th>网络浏览器</th> <th>驱动程序下载参考</th> </tr> </thead> <tbody> <tr> <td>谷歌浏览器/Chromium</td> <td><a href="https://chromedriver.storage.googleapis.com/index.html" target="_blank">下载</a></td> </tr> <tr> <td>Mozilla Firefox</td> <td><a href="https://github.com/mozilla/geckodriver/releases" target="_blank">下载</a></td> </tr> <tr> <td>微软 Edge</td> <td><a href="https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/" target="_blank">下载</a></td> </tr> <tr> <td>苹果 Safari</td> <td>已经内置</td> </tr> </tbody> </table> <p>Driver Download Links</p> <h2 id="使用驱动程序的方法">使用驱动程序的方法</h2> <p>现在让我们看看如何使用 selenium web 驱动程序。</p> <h3 id="1输入直接位置">1.输入直接位置</h3> <ul> <li>在 Python Selenium 代码中使用 web 驱动程序实现浏览器自动化的最流行的方法。它受欢迎的原因是它使用的直接方法,在脚本中定义驱动程序。</li> <li>这种方法需要手动下载 web 驱动程序。</li> </ul> <p><strong>优点</strong>:不需要关心冗长的设置或者计算出环境变量<br> 缺点:使得代码不太灵活,每次更新都需要手动修改</p> <pre><code class="language-py">driver = webdriver.Chrome('path/to/chromedriver") driver = webdriver.Chrome('C://software/chromedriver.exe') #driver located at the specified location driver = webdriver.Chrome('chromedriver.exe') #driver located in the same directory as of the python script file #other way service = Service(executable_path="/path/to/chromedriver") driver = webdriver.Chrome(service=service) </code></pre> <h3 id="2环境变量">2.环境变量</h3> <ul> <li>如果你尝试过上面提到的方法,那么你可能已经注意到在你电脑的某个目录中记下/记住你安装的 web 驱动的位置是多么的累人。</li> <li>为了解决这个问题,我们在环境变量中一劳永逸地定义了驱动程序的位置或路径。成功定义后,我们不需要在代码中指定路径位置,我们可以毫不费力地编码。</li> <li>这种方法也需要手动安装驱动程序,因为你可能已经知道这种方法是用于路径变量的问题。</li> </ul> <p><strong>优点</strong>:没有为驱动程序指定路径的麻烦<br> <strong>缺点</strong>:没有更新功能</p> <p>要设置环境路径变量,请在命令提示符下键入以下命令:使用驱动程序的路径(安装位置)代替下面命令中的“C:\WebDriver\bin”。</p> <pre><code class="language-py">setx PATH "%PATH%;C:\WebDriver\bin" </code></pre> <p>如果你觉得这种方法很难,那么你可以在你的 Windows 开始菜单中搜索环境变量,然后点击打开-" <strong>编辑系统环境变量</strong>。之后,从弹出窗口中选择<strong>环境变量</strong>,打开另一个弹出窗口。</p> <p>从<strong>系统变量</strong>选项中,选择打开<strong>路径</strong>,现在点击<strong>新建</strong>引入一个新的路径变量。粘贴你的网络驱动的位置在里面,然后确定,确定,最后再次确定,在所有窗口。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/926c9456d753f9582b4baa7910af7c60.png" alt="Environment Variable" loading="lazy"></p> <p>Environment Variable</p> <h3 id="3驱动程序经理">3.驱动程序经理</h3> <p>最后一个也可能是最有用的方法是 Python 代码中的 Web 驱动程序。在选择 Web 浏览器中的自动更新时,设备仅更新浏览器,而不更新已安装的驱动程序,在这种情况下,在执行 python 脚本时,代码会显示浏览器和驱动程序版本不同的错误。</p> <p><strong>优点</strong>:没有版本兼容性问题,有助于在多种浏览器之间轻松切换<br> <strong>缺点</strong>:对于初学者来说,设置起来可能有点困难</p> <p><strong>安装驱动管理器</strong></p> <pre><code class="language-py">pip install webdriver-manager </code></pre> <p><strong>导入经理</strong></p> <pre><code class="language-py">from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager # --> for Chrome #from webdriver_manager.firefox import GeckoDriverManager # --> for Firefox </code></pre> <p>现在,我们已经安装并导入了管理器,我们在代码中使用它,如下所示</p> <p>使用<code>**install()**</code>方法获取管理器使用的位置,并将其传递给 loc_service 类。此方法本身会通知已安装的 web 驱动程序的位置。</p> <pre><code class="language-py">driver = webdriver.Chrome(ChromeDriverManager().install()) # --> for Chrome #driver = webdriver.Firefox(executable_path=GeckoDriverManager().install()) #--> for Firefox </code></pre> <p>对于其他任何浏览器,可以查看驱动管理器软件的官方 <a href="https://github.com/SergeyPirogov/webdriver_manager" target="_blank">GitHub 库</a>。</p> <h2 id="结论-73">结论</h2> <p>教程到此为止。与 Selenium 中使用 web 驱动程序的流行方法相反,在本教程中,您了解了执行相同操作的其他方法,这些方法可能更有优势。</p> <h1 id="自然语言处理简介">自然语言处理简介</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/introduction-to-nlp" target="_blank">https://www.askpython.com/python/examples/introduction-to-nlp</a></p> </blockquote> <p>自然语言处理(NLP)是计算机科学的一部分,更具体地说是人工智能的一部分,它处理计算机与人类用自然语言进行的交互。人类使用自然语言作为交流的手段。</p> <p>自然语言处理旨在让计算机像人类一样理解自然语言,并生成它们。计算机可以理解结构化数据,如数据库中的表格,但人类语言是以文本和语音的形式存在的,这些是非结构化的数据形式。NLP 的应用范围从苹果的 Siri 这样的语音助手到机器翻译、文本过滤等概念。</p> <p>在本文中,我们将对自然语言处理进行概述。</p> <hr> <h2 id="nlp-难吗">NLP 难吗?</h2> <p>人类的语言很复杂。同样的事情在人类语言中可以用不同的方式表达。一个句子中使用的单词根据上下文和它们的用法可以有不同的意思。</p> <p>为了得出句子的正确意思,需要事先知道上下文。言语、手势和声音在人类语言交流中也起着重要的作用。NLP 很难,因为语言包含了歧义和不确定性。所有这些都是自然语言处理的一些挑战。</p> <hr> <h2 id="nlp-的组件">NLP 的组件</h2> <p>自然语言处理有以下两个组成部分:</p> <ol> <li><strong>自然语言理解</strong><br> 自然语言理解是指计算机理解人类语言的能力。它是重新排列非结构化数据以便计算机能够理解的过程。</li> <li><strong>自然语言生成</strong><br> 自然语言生成是从结构化或非结构化数据中生成人类可读文本的过程。</li> </ol> <hr> <h2 id="自然语言处理技术">自然语言处理技术</h2> <p>我们来看看常用的自然语言处理技术。这些技术包括句法技术,如<strong>词干化</strong>、<strong>词汇化</strong>、<strong>词性标注</strong>和 <strong><a href="https://www.askpython.com/python-modules/tokenization-in-python-using-nltk" target="_blank">标记化</a></strong> 以及语义技术,如<strong>命名实体识别</strong>和<strong>停用词移除</strong>。</p> <h3 id="堵塞物">堵塞物</h3> <p>词干化将一个单词简化为它的词干,即词根或基本形式。这是通过删除任何词缀添加到一个词。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6e30e89b6cbca9377194ec6cfa658601.png" alt="Stemming" loading="lazy"></p> <p>Stemming</p> <hr> <h3 id="词汇化">词汇化</h3> <p>词汇化是将单词转换成其词根的过程。这是借助词性标注和句子的上下文来确定单词的词根。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3c99c6809d6f88d2470238e9798760be.png" alt="Lemmatization" loading="lazy"></p> <p>Lemmatization</p> <hr> <h3 id="标记化">标记化</h3> <p>令牌是代表一个单词或其一部分的任何东西。这意味着即使是字符也可以被认为是记号。标记化是将句子分解成单个单词并存储它们的过程。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5d299a6e1b0db1d746ca232d3607be75.png" alt="Tokenization" loading="lazy"></p> <p>Tokenization</p> <hr> <h3 id="词性标注">词性标注</h3> <p>词性标注对于句法和语义分析非常重要,因为一个单词在给定的句子中可能有多个含义。在这种情况下,需要知道单词的具体含义,以便计算机进行适当的处理。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/49b796193c37684b83503d67f31cfc02.png" alt="Pos Tagging" loading="lazy"></p> <p>POS Tagging</p> <hr> <h3 id="命名实体识别">命名实体识别</h3> <p>自然语言处理中的命名实体识别(NER)是指将单词分类到子类别中的过程。NER 模型从识别感兴趣的实体开始,然后将其归类到最合适的类别。以下是一些最常见的命名实体类型的列表:</p> <ul> <li>人</li> <li>组织</li> <li>日期</li> <li>地方</li> </ul> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/da4645f574e37896113dbcf2a3ba7d91.png" alt="Ner" loading="lazy"></p> <p>Named Entity Recognition</p> <hr> <h3 id="停止单词删除">停止单词删除</h3> <p>停用词是句子中常用的词。停用词的例子有“is”、“the”、“in”、“a”、“an”等。这些是为了使句子语法正确而添加的,但是在开发模型时没有什么重要性,所以我们删除了它们。这也减小了数据集的大小。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e4f50de7fa55448626323842221158df.png" alt="Stop Words Removal" loading="lazy"></p> <p>Stop Words Removal</p> <p><em><strong>推荐阅读:<a href="https://www.askpython.com/python/top-python-libraries-for-natural-language-processing" target="_blank">用于 NLP 的 Python 库</a></strong></em></p> <hr> <h2 id="自然语言处理的应用">自然语言处理的应用</h2> <p>下面是我们在日常生活中使用的一些最常见的 NLP 应用。</p> <h3 id="邮件过滤器">邮件过滤器</h3> <p>NLP 最常见的应用是消息过滤。这意味着将信息分为不同的类别,如垃圾邮件、社交、促销等。基于一些关键词的存在。这项技术最受欢迎的应用是在 Gmail 中。</p> <h3 id="语言翻译">语言翻译</h3> <p>像 Google translate 这样的翻译工具使用自然语言处理将给定的句子从一种语言翻译成另一种语言。</p> <h3 id="虚拟助手">虚拟助手</h3> <p>虚拟助手不仅能理解用自然语言给出的命令,还能和你用同样的语言交谈。这类助手的例子有 Alexa、Siri、Google Home 等。</p> <h3 id="自动完成">自动完成</h3> <p>像自动更正、自动完成和预测文本这样的功能在我们的智能手机中很常见。他们分别纠正拼写,完成单词,并通过查看到目前为止键入的句子来预测或建议句子中的下一个单词。所有这些功能都利用了 NLP。</p> <hr> <h2 id="结论-74">结论</h2> <p>自然语言处理是人工智能的一个子领域,旨在帮助机器理解自然语言。NLP 在数字世界中有许多广泛的应用,它以创新的方式帮助改善了人机交互。</p> <h1 id="细流简介">细流简介</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/introduction-to-streamlit" target="_blank">https://www.askpython.com/python-modules/introduction-to-streamlit</a></p> </blockquote> <p>数据科学、数据分析和机器学习是过去几年中的一些新兴领域。采用上述技术的应用程序的开发有了巨大的增长,Python 是开发这种应用程序的首选语言。</p> <p>但是,仅仅为机器学习模型编写代码是不够的,因为普通人无法使用它。在这里,以任何人都可以轻松使用的方式部署我们的模型是很重要的。Python 中有不同的选项来部署我们的模型,如 Django 和 Flask 框架。在使用这些框架时,我们还需要了解使用 HTML、CSS 和 JS 构建前端的知识。</p> <p>如果我告诉你有一个更简单的方法呢?</p> <p>Streamlit 是一个开源框架,让你不仅可以部署机器学习模型,还可以在几分钟内部署任何 Python 应用。它还能让我们管理并与他人分享我们的应用程序。</p> <p>听起来很刺激,对吧?所以,让我们来探索 Streamlit 吧!</p> <hr> <h2 id="装置">装置</h2> <p>首先,让我们先安装 streamlit。这样做真的很容易。你需要在电脑上安装 <strong>Python 3.7-Python 3.10、Anaconda、PIP 和你最喜欢的 Python IDE</strong> 。然后,在 anaconda 终端中,只需运行以下命令来安装<code>streamlit</code>:</p> <pre><code class="language-py">pip install streamlit </code></pre> <p>此命令仅适用于 Windows。要在 Mac 和 Linux 上安装 Streamlit,请参考此处的。</p> <hr> <h2 id="在细流中创建-hello-world-应用程序">在细流中创建 hello world 应用程序</h2> <p>现在我们已经安装了 streamlit,让我们开始创建一个简单的“Hello World”应用程序。</p> <p>这个文件的名字是“ <strong>hello.py</strong> ”。</p> <pre><code class="language-py">import streamlit as st st.title("hello world") </code></pre> <p>要运行该应用程序,只需输入</p> <pre><code class="language-py">streamlit run hello.py </code></pre> <p>该应用将于<code>http://localhost:8501/</code>在您的默认网络浏览器中运行。</p> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/a97489f27a930aaf9a58425dba65b5fa.png" alt="Streamlit Hello Word" loading="lazy"></p> <p>Streamlit Hello Word</p> <hr> <h2 id="streamlit-中的文本元素">Streamlit 中的文本元素</h2> <p>现在让我们看看 Streamlit 提供的一些文本元素。</p> <p>| <strong>元素</strong> | <strong>描述</strong> |<br> | 标题 | 设置页面的标题 |<br> | 页眉 | 以标题格式显示文本 |<br> | Subheader | 以副标题格式显示文本 |<br> | 降价 | 对文本使用标记格式 |<br> | 密码 | 将文本显示为代码,并突出显示适当的语法 |<br> | 乳液 | 使用 latex 显示数学方程式 |</p> <p>Text Elements in Streamlit</p> <pre><code class="language-py">import streamlit as st # set the app's title st.title("Text Elements") # header st.header("Header in Streamlit") # subheader st.subheader("Subheader in Streamlit") # markdown # display text in bold formatting st.markdown("**AskPython** is an awesome website!") # display text in italic formatting st.markdown("Visit _askpython.com_ to learn from various Python tutorials.") # code block code = ''' def add(a, b): print("a+b = ", a+b) ''' st.code(code, language='python') # latex st.latex(''' (a+b)^2 = a^2 + b^2 + 2*a*b ''') </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/b3830383a7c14d7b861c76a5a0b795e2.png" alt="Streamlit Text Elements" loading="lazy"></p> <p>Streamlit Text Elements</p> <p>在上面的代码中,我们首先导入了 streamlit,并添加了上表中讨论的每个文本元素。这里的语法也很容易理解。</p> <p>在 <strong>markdown</strong> 部分,我们使用<code>** **</code>将文本<strong>加粗</strong>并使用<code>_ _</code>将其倾斜,就像我们一直做的那样。</p> <p>此外,在<strong>代码块</strong>中,我们已经将<strong>语言</strong>指定为“ <strong>Python</strong> ”,以便根据需要突出显示代码。我们可以根据自己的需要指定任何语言。</p> <p>现在,让我们来看看 <strong>Streamlit</strong> 中的一些小部件。</p> <h2 id="细流中的小组件">细流中的小组件</h2> <p>有了 widgets,我们可以通过使用按钮、滑块等使我们的应用程序具有交互性。</p> <h3 id="细流中的按钮">细流中的按钮</h3> <pre><code class="language-py">import streamlit as st #button if st.button('Click here', help="Click to see the text change"): st.write('Hi there!') else: st.write('Goodbye') </code></pre> <p><strong>输出:</strong></p> <p>上面的代码由一个显示“点击这里”的按钮组成。在创建按钮时,我们还使用“help”参数添加了一个工具提示。如果按钮被点击,“你好!”将打印在屏幕上,否则将打印“再见”。</p> <h3 id="细流中的复选框">细流中的复选框</h3> <pre><code class="language-py">import streamlit as st # check box checked = st.checkbox('Click here') if checked: st.write('Good job!') </code></pre> <p><strong>输出:</strong></p> <p>短信“干得好!”仅当复选框被选中时才显示。</p> <h3 id="细流中的单选按钮">细流中的单选按钮</h3> <pre><code class="language-py">import streamlit as st # radio button lang = st.radio( "What's your favorite programming language?", ('C++', 'Python')) if lang == 'C++': st.write('You selected C++.') else: st.write('You selected Python.') </code></pre> <p><strong>输出:</strong></p> <p>在这个例子中,我们有一个单选按钮,其中我们问了一个问题并给了用户两个选项。默认情况下选择第一个选项,如果用户选择第二个选项,将相应地显示文本。</p> <h3 id="细流中的滑块">细流中的滑块</h3> <pre><code class="language-py">import streamlit as st # slider score = st.slider('Please specify your test score', min_value=0, max_value=100, value=10) st.write("My test score is ", score) </code></pre> <p><strong>输出:</strong></p> <p>这是一个简单的滑块,<code>min_value=0</code>是滑块中的最小值,也是默认的最小值,<code>max_value=100</code>是滑块中的最大值,<code>d</code> <code>value=10</code>指定最初显示的值。所有这些值都可以根据我们的要求进行更改。</p> <hr> <h2 id="结论-75">结论</h2> <p>本教程到此为止!这是 Streamlit 教程系列的第一篇。也请查看本系列中的其他教程。</p> <hr> <h2 id="参考-12">参考</h2> <ul> <li><a href="https://docs.streamlit.io/" target="_blank">简化官方文档</a></li> </ul> <h1 id="反转布尔数组的元素">反转布尔数组的元素</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/numpy/invert-elements-of-a-boolean-array" target="_blank">https://www.askpython.com/python-modules/numpy/invert-elements-of-a-boolean-array</a></p> </blockquote> <p>在这篇文章中,我们将学习如何反转一个布尔数组的元素,该数组包含布尔值,如 True 或 False。</p> <h2 id="python-中的布尔数组是什么">Python 中的布尔数组是什么?</h2> <p>布尔数组是一个有布尔值的数组,比如真或假,或者可能是 1 或 0。使用 dtype = bool 可以形成布尔数组。除了 0、无、假或空字符串之外,其他都被认为是真的。</p> <pre><code class="language-py">import numpy as np arr_bool = np.array([1, 1.1, 0, None, 'a', '', True, False], dtype=bool) print(arr_bool) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">[ True True False False True False True False] </code></pre> <h2 id="反转布尔数组元素的方法">反转布尔数组元素的方法</h2> <p>以下是在 Python 中反转布尔数组元素的方法。</p> <h3 id="使用-npinvert函数">使用 np.invert()函数</h3> <p>使用内置的 np。invert()函数可以反转一个布尔数组的元素。</p> <pre><code class="language-py">import numpy as np arr = np.array((True, True, False, True, False)) arr_inver = np.invert(arr) print(arr_inver) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">[False False True False True] </code></pre> <h3 id="使用-if-else-方法">使用 if-else 方法</h3> <p>在这个方法中,我们将检查数组中每个元素的索引值。如果该值为零,它将被更改为 1,反之亦然。此外,如果值为 True,它将被更改为 False。</p> <pre><code class="language-py">arr = ((0, 1, 0, 1)) a1 = list(arr) for x in range(len(a1)): if(a1[x]): a1[x] = 0 else: a1[x] = 1 print(a1) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">[1, 0, 1, 0] </code></pre> <h2 id="结论-76">结论</h2> <p>总之,我们学习了在 python 中反转布尔数组元素的不同方法。Numpy 是一个灵活的 python 库,并提供了多种功能。</p> <h1 id="python-中的-ipaddress-模块简单示例">Python 中的 ipaddress 模块[简单示例]</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/ipaddress-module" target="_blank">https://www.askpython.com/python-modules/ipaddress-module</a></p> </blockquote> <p>嘿伙计们!今天我们将学习 Python 中的 ipaddress 模块。所以事不宜迟,让我们开始吧。</p> <h2 id="什么是-ip-地址">什么是 IP 地址?</h2> <p>IP 代表互联网协议。它用于识别任何网络上的节点。因此,任何连接到互联网的设备都需要拥有一个 IP 地址。</p> <p>IP 地址有两种版本:IPv4 和 IPv6。目前使用的是 IPv4,而由于与网络上的设备相比,IPv4 地址的短缺,主要网络提供商正在缓慢地采用 IPv6。</p> <p>要了解更多关于 IP 地址的信息,请点击查看 <a href="https://en.wikipedia.org/wiki/IP_address" target="_blank">Wiki 页面。</a></p> <h2 id="python-中的-ipaddress-模块怎么用">Python 中的 ipaddress 模块怎么用?</h2> <p>现在让我们从使用 ipaddressmodule 开始。要设置主机地址,我们使用 <em>ipaddress.ip_address( )</em> 。</p> <p>该函数根据传递的值自动确定使用哪个版本。它要么返回 IPv4 地址,要么返回 IPv6 地址。</p> <h3 id="1如何创建有效的-ipv4-地址">1.如何创建有效的 IPv4 地址?</h3> <p>IPv4 验证 0 到 255 范围内的值。适合 32 位的整数代表地址中的一个二进制八位数。一个长度为 4 的被打包到字节对象中的整数。</p> <pre><code class="language-py">import ipaddress ipaddress.ip_address('199.138.0.1') </code></pre> <p>输出:</p> <pre><code class="language-py">IPv4Address('199.138.0.1') </code></pre> <h3 id="2如何创建有效的-ipv6-地址">2.如何创建有效的 IPv6 地址?</h3> <p>IPv6 验证范围从 0 到 ffff 的值。适合 128 位的整数。一个长度为 16 的整数,被打包到一个字节对象中。</p> <pre><code class="language-py">import ipaddress ipaddress.ip_address('2011:cb0::') ipaddress.ip_address('FFFF:9999:2:FDE:257:0:2FAE:112D') </code></pre> <p>输出:</p> <pre><code class="language-py">IPv6Address('2011:cb0::') IPv6Address('ffff:9999:2:fde:257:0:2fae:112d') </code></pre> <h2 id="使用-ipaddress-模块在-python-中处理-ip-地址">使用 ipaddress 模块在 Python 中处理 IP 地址</h2> <p>IP 地址伴随着一套规则。IP 地址的范围被分配了不同的功能。</p> <p>例如,127.0.0.1 是分配给计算机网络模块的环回地址。当你向这个 IP 地址发送 ping 数据包时,你实际上是在 ping 你自己的计算机。</p> <h3 id="1基本-ip-功能">1.基本 IP 功能</h3> <p>让我们看看如何使用 Python 中的 ipaddress 模块来验证哪些地址是回送地址、多播地址、本地链路地址或保留地址</p> <pre><code class="language-py">import ipaddress ipa = ipaddress.ip_address('199.138.0.1') print(ipa.is_private) # Checks if address is private print(ipa.is_global) # Checks if address is global #If address is a loopback address print(ipaddress.ip_address("127.0.0.1").is_loopback) #If address is reserved for multiclass use print(ipaddress.ip_address("229.100.0.23").is_multicast) #If address is reserved for link local usage print(ipaddress.ip_address("169.254.0.100").is_link_local) #True if the address is otherwise IETF reserved. print(ipaddress.ip_address("240.10.0.1").is_reserved) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">False True True True True True </code></pre> <h3 id="2反向-ip-查找">2.反向 IP 查找</h3> <p>反向指针函数请求 DNS 解析此处作为参数添加的 IP 地址。如果 DNS 能够解析 IP,您将收到一个带有指定名称的输出。</p> <p>如果您 ping 一个分配给某个域名的 IP,您很可能会得到该域名所在的服务器的名称。但是,这可能会根据防火墙的设置而改变。</p> <pre><code class="language-py">ipaddress.ip_address("199.138.0.1").reverse_pointer </code></pre> <p>输出:</p> <pre><code class="language-py">'1.0.138.199.in-addr.arpa' </code></pre> <h1 id="使用-ip-地址模块处理-ip-网络">使用 IP 地址模块处理 IP 网络</h1> <p>IP 网络和 IPv6 网络可以帮助用户定义和检查 IP 网络定义。</p> <p>我们不需要编写自定义代码就可以得到我们需要的格式的 IP 网络。</p> <ol> <li><em>前缀/ < nbits ></em> 表示网络掩码中设置的高位位数。</li> <li>2.网络掩码是一个 IP 地址,包含许多高位位。</li> <li>3.主机掩码是<em>网络掩码</em>的逻辑逆,用于 Cisco 访问控制列表。</li> </ol> <pre><code class="language-py">ipn = ipaddress.ip_network("10.0.0.0/16") print(ipn.with_prefixlen) print(ipn.with_hostmask) print(ipn.with_netmask) </code></pre> <p>输出:</p> <pre><code class="language-py">10.0.0.0/16 10.0.0.0/0.0.255.255 10.0.0.0/255.255.0.0 </code></pre> <h3 id="1检查-ip-地址是-ipv4-还是-ipv6">1.检查 IP 地址是 IPv4 还是 IPv6</h3> <p><em>ipaddress.ip_network( )</em> 函数用于返回网络类型的地址。它确认 IP 是在 IP4 网络还是 IP6 网络中。</p> <pre><code class="language-py">import ipaddress ipaddress.ip_network('199.138.0.1') ipaddress.ip_network('FFFF:9999:2:FDE:257:0:2FAE:112D') </code></pre> <p>输出:</p> <pre><code class="language-py">IPv4Network('199.138.0.1/32') IPv6Network('ffff:9999:2:fde:257:0:2fae:112d/128') </code></pre> <h3 id="2识别-ip-网络上的主机">2.识别 IP 网络上的主机</h3> <p>主机是属于网络的所有 IP 地址,除了网络地址和网络广播地址。</p> <p><em>host( )</em> 返回网络中可用主机的迭代器。</p> <p>掩码长度为 31 的网络,网络地址和网络广播地址也包括在结果中,掩码长度为 32 的网络返回单个主机地址的返回列表。</p> <pre><code class="language-py">ipn= ipaddress.ip_network('192.0.2.0/29') list(ipn.hosts()) </code></pre> <p>输出:</p> <pre><code class="language-py">[IPv4Address('192.0.2.1'), IPv4Address('192.0.2.2'), IPv4Address('192.0.2.3'), IPv4Address('192.0.2.4'), IPv4Address('192.0.2.5'), IPv4Address('192.0.2.6')] </code></pre> <h3 id="3识别网络的广播地址">3.识别网络的广播地址</h3> <p>使用 broadcast_address,我们可以请求 DNS 服务器使用网络上的广播地址进行响应。</p> <pre><code class="language-py">ipn= ipaddress.ip_network('199.1.8.0/29') ipn.broadcast_address </code></pre> <p>输出:</p> <pre><code class="language-py">IPv4Address('199.1.8.7') </code></pre> <h3 id="4识别-ip-网络重叠">4.识别 IP 网络重叠</h3> <p>这个函数告诉我们,如果一个网络部分或全部包含在另一个网络中。它返回 true 或 false。</p> <pre><code class="language-py">ipn1 = ipaddress.ip_network("10.10.1.32/29") ipn2 = ipaddress.ip_network("10.10.1.32/27") ipn3 = ipaddress.ip_network("10.10.1.48/29") print(ipn1.overlaps(ipn2)) print(ipn1.overlaps(ipn3)) print(ipn3.overlaps(ipn2)) </code></pre> <p>输出:</p> <pre><code class="language-py">True False True </code></pre> <h3 id="5ip-网络上的子网">5.IP 网络上的子网</h3> <p>它返回网络对象的一个<a href="https://www.askpython.com/python/built-in-methods/python-iterator" target="_blank">迭代器</a>。prefixlen_diff 是应该增加的前缀长度,new_prefix 是子网的新前缀,大于我们的前缀。</p> <pre><code class="language-py">ipn1 = ipaddress.ip_network("10.10.1.32/29") print(list(ipn1.subnets())) print(list(ipn1.subnets(prefixlen_diff=2))) print(list(ipn1.subnets(new_prefix=30))) </code></pre> <p>输出:</p> <pre><code class="language-py">[IPv4Network('10.10.1.32/30'), IPv4Network('10.10.1.36/30')] [IPv4Network('10.10.1.32/31'), IPv4Network('10.10.1.34/31'), IPv4Network('10.10.1.36/31'), IPv4Network('10.10.1.38/31')] [IPv4Network('10.10.1.32/30'), IPv4Network('10.10.1.36/30')] </code></pre> <h3 id="6使用-ipaddress-模块创建超网">6.使用 ipaddress 模块创建超网</h3> <p>超网是一个或多个子网的组合。你可以<a href="https://en.wikipedia.org/wiki/Supernetwork" target="_blank">在这里</a>了解更多关于超网的信息。使用 ipaddress 模块中的超网方法,您可以根据需要指定信息来创建子网。</p> <ul> <li>前缀长度应该增加多少</li> <li><em>new_prefix</em> 是子网的所需新前缀,应该大于我们的前缀。</li> </ul> <pre><code class="language-py">ipnn = ipaddress.ip_network("172.10.15.160/29") print(ipnn.supernet(prefixlen_diff=3)) print(ipnn.supernet(new_prefix=20)) </code></pre> <p>输出:</p> <pre><code class="language-py">172.10.15.128/26 172.10.0.0/20 </code></pre> <h3 id="7检查一个-ip-网络是否是另一个-ip-网络的超网子网">7.检查一个 IP 网络是否是另一个 IP 网络的超网/子网</h3> <p>如果一个网络是另一个网络的子网,或者如果一个网络是另一个网络的超网,则返回 true。返回真或假。</p> <pre><code class="language-py">a = ipaddress.ip_network("192.168.1.0/24") b = ipaddress.ip_network("192.168.1.128/30") print(b.subnet_of(a)) print(a.supernet_of(b)) </code></pre> <p>输出:</p> <pre><code class="language-py">True True </code></pre> <h3 id="8使用-with-接口对象">8.使用 with 接口对象</h3> <p>接口对象可以用作字典中的键,因为它们是可散列的。</p> <p>IPv4Interface 继承了 IPv4Address 的所有属性,因为 IPv4Interface 是 IPv4Address 的子类。</p> <p>这里,<em>199.167.1.6</em>的 IP 地址在网络 <em>199.167.1.0/24</em></p> <pre><code class="language-py">from ipaddress import IPv4Interface ifc = IPv4Interface("199.167.1.6/24") print(ifc.ip) print(ifc.network) </code></pre> <p>输出:</p> <pre><code class="language-py">199.167.1.6 199.167.1.0/24 </code></pre> <p>我们可以用前缀表示法将网络接口表示为网络掩码和主机掩码。</p> <pre><code class="language-py">interface = IPv4Interface('192.0.2.5/24') print(interface.with_prefixlen) print(interface.with_netmask) print(interface.with_hostmask) </code></pre> <p>输出:</p> <pre><code class="language-py">192.0.2.5/24 192.0.2.5/255.255.255.0 192.0.2.5/0.0.0.255 </code></pre> <h2 id="使用-ip-地址的杂项操作">使用 IP 地址的杂项操作</h2> <p>使用 Python 中的<a href="https://www.askpython.com/python/python-comparison-operators" target="_blank">比较运算符,你可以检查一个 IP 地址与另一个的比较情况。看看下面的例子。</a></p> <pre><code class="language-py">ipa1=ipaddress.ip_address("127.0.0.2") ipa2=ipaddress.ip_address("127.0.0.1") print(ipa1>ipa2) print(ipa1==ipa2) print(ipa1!=ipa2) </code></pre> <p>输出:</p> <pre><code class="language-py">True False True </code></pre> <p>我们可以从 IP 地址对象中加减整数。</p> <pre><code class="language-py">ipa = ipaddress.ip_address("10.10.1.0") print( ipa + 9) </code></pre> <p>输出:</p> <pre><code class="language-py">10.10.1.9 </code></pre> <p><strong>通过使用内置函数 <em>str( )</em> 和 <em>int(),可以将地址转换成字符串或整数。</em></strong></p> <pre><code class="language-py">str(ipaddress.IPv4Address('199.138.0.1')) int(ipaddress.IPv4Address('192.198.0.1')) </code></pre> <p>输出:</p> <pre><code class="language-py">'199.138.0.1' 3234201601 </code></pre> <p>IPv6 地址被转换成不带区域 ID 的字符串。</p> <pre><code class="language-py">str(ipaddress.IPv6Address('::8')) int(ipaddress.IPv6Address('::100')) </code></pre> <p>输出:</p> <pre><code class="language-py">'::8' 256 </code></pre> <h2 id="结论-77">结论</h2> <p>在本教程中,我们学习了 IPv4 和 IPv6 地址、网络和接口。更多此类内容,敬请关注。快乐学习!🙂</p> <h2 id="参考-13">参考</h2> <p><a href="https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network" target="_blank">IP 地址模块正式文档</a></p> <h1 id="基于多种最大似然算法的虹膜数据集分类">基于多种最大似然算法的虹膜数据集分类</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/iris-dataset-classification" target="_blank">https://www.askpython.com/python/examples/iris-dataset-classification</a></p> </blockquote> <p>你好。今天我们将学习一个新的数据集——虹膜数据集。数据集非常有趣,因为它处理花的各种属性,然后根据它们的属性对它们进行分类。</p> <h2 id="1导入模块-3">1.导入模块</h2> <p>任何项目的第一步都是导入基本模块,包括 <a href="https://www.askpython.com/python-modules/numpy/python-numpy-module" target="_blank">numpy</a> 、 <a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">pandas</a> 和 <a href="https://www.askpython.com/python-modules/matplotlib/python-matplotlib" target="_blank">matplotlib</a> 。</p> <pre><code class="language-py">import numpy as np import pandas as pd import matplotlib.pyplot as plt </code></pre> <h2 id="2加载和准备-iris-数据集">2.加载和准备 Iris 数据集</h2> <p>为了加载数据,我们将从 Kaggle 下载数据集。你可以在这里下载数据集<a href="https://www.kaggle.com/uciml/iris" target="_blank">,但是要确保这个文件和代码文件在同一个目录下。</a></p> <p>我们还将通过对数据进行切片操作来将数据和标签相互分离。</p> <pre><code class="language-py">data = pd.read_csv('Iris.csv') data_points = data.iloc[:, 1:5] labels = data.iloc[:, 5] </code></pre> <h2 id="3将数据分为测试数据和训练数据">3.将数据分为测试数据和训练数据</h2> <p>在训练任何一种 ML 模型之前,我们首先需要使用 sklearn 的<code>train_test_split</code>函数将数据<a href="https://www.askpython.com/python/examples/split-data-training-and-testing-set" target="_blank">分割成测试和训练数据</a>。</p> <pre><code class="language-py">from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(data_points,labels,test_size=0.2) </code></pre> <h2 id="4数据的标准化规范化">4.数据的标准化/规范化</h2> <p>在我们进行 ML 建模和数据处理之前,我们需要对数据进行规范化,下面将提到代码。</p> <pre><code class="language-py">from sklearn.preprocessing import StandardScaler from sklearn.model_selection import cross_val_score Standard_obj = StandardScaler() Standard_obj.fit(x_train) x_train_std = Standard_obj.transform(x_train) x_test_std = Standard_obj.transform(x_test) </code></pre> <h2 id="5应用分类-ml-模型">5.应用分类 ML 模型</h2> <p>现在我们的数据已经准备好,可以进入各种 ML 模型,我们将测试和比较各种分类模型的效率</p> <h3 id="51-svm支持向量机">5.1 SVM(支持向量机)</h3> <p>我们要测试的第一个模型是 SVM 分类器。下面提到了相同的代码。</p> <pre><code class="language-py">from sklearn.svm import SVC svm = SVC(kernel='rbf', random_state=0, gamma=.10, C=1.0) svm.fit(x_train_std, y_train) print('Training data accuracy {:.2f}'.format(svm.score(x_train_std, y_train)*100)) print('Testing data accuracy {:.2f}'.format(svm.score(x_test_std, y_test)*100)) </code></pre> <p>在成功执行时,分类器分别给出了大约 97%和 93%的训练和测试精度,这是相当不错的。</p> <h3 id="52-knn-k-近邻">5.2 KNN (K 近邻)</h3> <p><a href="https://www.askpython.com/python/examples/knn-in-python" target="_blank">KNN 算法</a>是 ML 世界中最基本、最简单、最初级的分类模型之一。直接执行它的代码如下所示。</p> <pre><code class="language-py">from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors = 7, p = 2, metric='minkowski') knn.fit(x_train_std,y_train) print('Training data accuracy {:.2f}'.format(knn.score(x_train_std, y_train)*100)) print('Testing data accuracy {:.2f}'.format(knn.score(x_test_std, y_test)*100)) </code></pre> <p>在这种情况下,测试精度只有大约 80%,与其他模型相比,这要低一些,但是这是合理的,因为该模型非常基本,并且有一些限制。</p> <h3 id="53-决策树">5.3 决策树</h3> <p>接下来,我们将实现决策树模型,这是一个简单而复杂的 ML 模型。相同的代码如下所示。</p> <pre><code class="language-py">from sklearn import tree decision_tree = tree.DecisionTreeClassifier(criterion='gini') decision_tree.fit(x_train_std, y_train) print('Training data accuracy {:.2f}'.format(decision_tree.score(x_train_std, y_train)*100)) print('Testing data accuracy {:.2f}'.format(decision_tree.score(x_test_std, y_test)*100)) </code></pre> <p>这个模型的测试准确率也仍然在 80%左右,因此到目前为止 SVM 给出了最好的结果。</p> <h3 id="54-随机森林">5.4 随机森林</h3> <p>随机森林是机器学习中更复杂、更好的决策树。相同的实现如下所示。</p> <pre><code class="language-py">from sklearn.ensemble import RandomForestClassifier random_forest = RandomForestClassifier() random_forest.fit(x_train_std, y_train) print('Training data accuracy {:.2f}'.format(random_forest.score(x_train_std, y_train)*100)) print('Testing data accuracy {:.2f}'.format(random_forest.score(x_test_std, y_test)*100)) </code></pre> <p>这里的准确率非常高,训练数据是 100%,这太棒了!而测试数据的准确率为 90%,这也是相当不错的。</p> <h2 id="结论-78">结论</h2> <p>恭喜你!本教程提到了在同一数据集上的许多不同的算法,我们为每个模型获得了不同的结果。希望你喜欢它!继续阅读,了解更多!</p> <p>感谢您的阅读!</p> <h1 id="python-中的-iterable-和-iterator-有什么区别">Python 中的 Iterable 和 Iterator 有什么区别?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/iterable-vs-iterator" target="_blank">https://www.askpython.com/python/iterable-vs-iterator</a></p> </blockquote> <p>在本教程中,我们将讨论 Python 中 iterable 和 iterator 的区别。</p> <hr> <h2 id="理解可迭代与迭代器">理解可迭代与迭代器</h2> <p>在 Python 中,我们可以循环或迭代的任何东西都被称为<strong>可迭代的</strong>。当我们将一个 iterable 对象传递给 Python 中的<code>iter()</code>函数时,它会返回一个迭代器。</p> <p>在 Python 中,<strong>迭代器</strong>是一个对象,通过将它传递给<code>iter()</code>函数从一个可迭代对象中获得。迭代器保存可被迭代的可数个值。迭代器用于迭代列表、字符串、元组等可迭代对象。在 Python 中。在迭代器的迭代中,它逐个返回每个元素。</p> <p><em><strong>注意:Python 中的每个可迭代对象不是迭代器,但每个迭代器都是可迭代的。</strong></em></p> <h2 id="python-中的-iterables">Python 中的 Iterables</h2> <p>在 Python 中,有五个众所周知的可迭代对象。让我们逐一讨论。</p> <h3 id="1目录">1.目录</h3> <p>一个<strong>列表</strong>是 Python 中最常用的可迭代对象之一。它以有序的方式存储数据元素。让我们创建一个 <a href="https://www.askpython.com/python/difference-between-python-list-vs-array" target="_blank">Python 列表</a>并迭代它。</p> <pre><code class="language-py"># Create a Python list list = ["JournalDev", "AskPython", "LinuxforDevices"] print("This is a Python list:") print(list) # Iterate through the Python list # using a for loop print("Iterating a Python list:") for element in list: print(element) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is a Python list: ['JournalDev', 'AskPython', 'LinuxforDevices'] Iterating a Python list: JournalDev AskPython LinuxforDevices </code></pre> <h3 id="2元组">2.元组</h3> <p>一个<strong>元组</strong>是 Python 中另一个常用的可迭代对象。像 Python 列表一样,它也以有序的方式存储数据元素。但是元组和列表之间唯一的关键区别是——在 Python 中,元组是不可变对象,而列表是可变对象。让我们创建一个 Python 元组并迭代它。</p> <pre><code class="language-py"># Create a Python tuple tuple = ('C', 'C++', 'Python', 'Java') print("This is a Python tuple:") print(tuple) # Iterate through the Python tuple # using a for loop print("Iterating a Python tuple:") for element in tuple: print(element) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is a Python tuple: ('C', 'C++', 'Python', 'Java') Iterating a Python tuple: C C++ Python Java </code></pre> <h3 id="3线">3.线</h3> <p>一个 <strong><a href="https://www.askpython.com/python/string/strings-in-python" target="_blank">字符串</a></strong> 也是 Python 中最常用的可迭代对象之一。在 Python 中,任何用单引号、双引号或三引号括起来的东西都称为字符串。它可以是单行字符串,也可以是多行字符串。让我们创建一个 Python 字符串并迭代它。</p> <pre><code class="language-py"># Create a Python string string = "PYTHON" print("This is a Python string: " + string) # Iterate through the Python string # using a for loop print("Iterating a Python string:") for element in string: print(element) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is a Python string: PYTHON Iterating a Python string: P Y T H O N </code></pre> <h3 id="4一组">4.一组</h3> <p>一个 <strong><a href="https://www.askpython.com/python/numpy-set-operations" target="_blank">集合</a></strong> 也是 Python 中一个非常著名的可迭代对象。它类似于 Python 中的列表和元组,但唯一的关键区别是——集合中不允许有重复的元素。让我们创建一个 Python 集并迭代它。</p> <pre><code class="language-py"># Create a Python set set = {"Go", "Dart", "Python", "Go"} print("This is a Python set:") print(set) # Iterate through the Python set # using a for loop print("Iterating a Python set:") for element in set: print(element) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is a Python set: {'Go', 'Python', 'Dart'} Iterating a Python set: Go Python Dart </code></pre> <h3 id="5词典">5.词典</h3> <p>一个 <strong><a href="https://www.askpython.com/python/dictionary/python-dictionary-dict-tutorial" target="_blank">字典</a></strong> 是 Python 中另一个非常广泛使用的可迭代对象。它用于以 key: value 格式存储数据,其中键必须是单值实体,而其对应的值可以是单值实体或多值实体。让我们创建一个 Python 字典并迭代它。</p> <pre><code class="language-py"># Create a Python dictionary dict = {'py': 'PYTHON', 'mat': 'MATLAB', 'cpp': 'C++'} print("This is a Python dictionary:") print(dict) # Iterate through the Python dictionary # using a for loop print("Iterating a Python dictionary:") for key in dict: print(key + '-' + dict[key]) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">This is a Python dictionary: {'py': 'PYTHON', 'mat': 'MATLAB', 'cpp': 'C++'} Iterating a Python dictionary: py-PYTHON mat-MATLAB cpp-C++ </code></pre> <h2 id="python-中的迭代器">Python 中的迭代器</h2> <p>当我们在 Python 中创建迭代器类的对象时,技术上有两个方法与之相关联。这两种方法属于迭代器类,统称为<strong>迭代器协议</strong>。</p> <h3 id="方法-1-iter">方法 1: <strong>iter</strong>()</h3> <p>在 Python 中,当我们试图通过将 iterable 对象传递给 iter()函数来创建迭代器对象时,会自动调用<code>__iter__()</code>方法。它用于从 iterable 对象初始化 iterator 对象。这个方法返回一个迭代器对象,可以用来迭代列表、元组、字典等可迭代对象。</p> <h3 id="方法-2__-下一个-_-_">方法 2:__ 下一个 _ _()</h3> <p>在 Python 中,当我们试图迭代 iterable 对象时,会自动调用<code>__next__()</code>方法。它用于遍历迭代器对象的所有元素。当应用于迭代器时,它返回 iterable 对象的下一个元素或值。当<code>__next__()</code>方法返回的可迭代对象中没有项目或元素时,通过引发<code>StopIteration</code>异常,它在停止可迭代对象的迭代中起着非常关键的作用。</p> <h2 id="如何转换-iterables-迭代器">如何转换 iterables ➔迭代器?</h2> <p>在 Python 中,我们可以很容易地转换列表、元组、集合等可迭代对象。简单地通过使用 iterable 对象到<code>iter()</code>函数,然后调用 iterable 对象上的<code>__iter__()</code>方法,iterable 对象被传递到<code>iter()</code>函数。</p> <p>让我们从 Python 中的 iterable 对象创建一个 iterator 对象,并分析 iterator 类的<code>__iter__()</code>和<code>__next__()</code>方法的工作原理。</p> <pre><code class="language-py"># Create an iterable object # here it's a Python list iterable_obj = ['HTML', 'CSS', 'JAVA SCRIPT'] print(type(iterable_obj)) print(iterable_obj) # Create an iterator object # from the above iterable object (Python list) # using the __iter__() method iterator_obj = iterable_obj.__iter__() print(type(iterator_obj)) # Iterate through the iterable object # using its iterator object & the __next__() method print(iterator_obj.__next__()) print(iterator_obj.__next__()) print(iterator_obj.__next__()) # Raise the StopIteration Exception print(iterator_obj.__next__()) </code></pre> <p><strong>输出:</strong></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/0c8201fa3ac63a81d07f3766349e8b8c.png" alt="Output Iterator Object Creation" loading="lazy"></p> <p>Output: iterator object creation</p> <p>在上面的 Python 代码中,我们创建了一个 iterable 对象(Python 列表),使用 <strong>iter</strong>()方法将其转换为 iterator 对象,使用 <strong>next</strong>()方法访问 iterable 对象的元素,并分析了当 <strong>next</strong>()方法被调用来访问 iterable 对象的下一个元素但 iterable 对象中没有剩余元素时,该方法如何引发 StopIteration 异常。</p> <h2 id="使用-for-循环迭代-iterable-对象">使用 for 循环迭代 iterable 对象</h2> <p>我们已经看到了上面的 iterable 对象的例子,循环的<a href="https://www.askpython.com/course/python-course-for-loop" target="_blank">被广泛用于在 Python 中迭代 iterable 对象的元素。让我们通过 Python 代码来分析迭代器的 for 循环的工作原理。</a></p> <pre><code class="language-py"># Create an iterable object here it's a Python tuple iterable = ('macOS', 'Linux', 'Windows') print(type(iterable)) print(iterable) # Iterate through the iterable object using a for loop print("Iteration using for loop:") for item in iterable: print(item) # Analyze the implemention of for loop to iterate through the elements of # the iterable object (Python tuple) using an infinite while loop and iterator protocol def for_loop(iterable): # Create an iterator object from the passed iterable object # using the iter() function iterator = iter(iterable) # Run an infinite while loop while True: try: # Access the each element of the iterable object # using the next() function print(next(iterator)) except StopIteration: # If the StopIteration Exception is raised # by the next() function break the while loop break # Driver Code to check the implementation of the for_loop() function print("Iteration using for_loop function:") for_loop(iterable) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py"><class 'tuple'> ('macOS', 'Linux', 'Windows') Iteration using for loop: macOS Linux Windows Iteration using for_loop function: macOS Linux Windows </code></pre> <p>从上面的 Python 代码中,我们已经理解了用于循环迭代可迭代对象元素的<strong>实际上是通过</strong>无限 while 循环<strong>实现的。当我们使用 for 循环迭代 iterable 对象时,首先创建一个迭代器对象,调用<code>iter()</code>函数,然后运行一个无限 while 循环,在该循环中使用<code>next()</code>函数来访问 iterable 对象的下一个元素,当由于 iterable 对象的元素耗尽而由<code>next()</code>函数引发<code>StopIteration</code>异常时,迭代停止。</strong></p> <h2 id="结论-79">结论</h2> <p>在本教程中,我们学习了以下内容。</p> <ol> <li>Python 中可迭代对象和迭代器对象的区别</li> <li>迭代器协议,即迭代器类的 <strong>iter</strong>()和 <strong>next</strong>()方法</li> <li>将可迭代对象转换为迭代器对象</li> <li>使用 for 循环迭代 iterable 对象的元素</li> </ol> <h1 id="如何迭代熊猫-dataframe-中的行">如何迭代熊猫 Dataframe 中的行?</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python-modules/pandas/iterate-over-rows-dataframe" target="_blank">https://www.askpython.com/python-modules/pandas/iterate-over-rows-dataframe</a></p> </blockquote> <p>“迭代”一词意味着一个接一个地获取数据结构中包含的每个元素的过程。在 python 中,我们使用循环多次遍历条目。我们也可以将迭代称为“项目的重复执行”。Pandas 是 Python 中一个非常有用的库,因为它提供了许多数据分析工具。在本文中,我们将学习如何在 Pandas 数据帧中迭代行。所以让我们开始吧!</p> <h2 id="熊猫的数据框架是什么">熊猫的数据框架是什么?</h2> <p>Pandas DataFrame 是由行和列组成的二维表格数据结构。DataFrame 是 Python 中的可变数据结构。</p> <p>例如:</p> <pre><code class="language-py">import pandas as pd #Creating the data data = {'Name':['Tommy','Linda','Justin','Brendon'], 'Marks':[100,200,300,600]} df= pd.DataFrame(data) print(df) </code></pre> <p>输出:</p> <pre><code class="language-py"> Name Marks 0 Tommy 100 1 Linda 200 2 Justin 300 3 Brendon 600 </code></pre> <p>现在让我们来看看迭代行的方法。</p> <h2 id="在-pandas-数据帧中迭代行的方法">在 Pandas 数据帧中迭代行的方法</h2> <p>有许多方法可以用来迭代 Pandas 数据帧中的行,但是每种方法都有自己的优点和缺点。</p> <h3 id="1使用-iterrows方法">1.使用 iterrows()方法</h3> <p>这是 Python 中迭代行的简单明了的方法之一。虽然这是最简单的方法,但迭代进行得很慢,效率也不高。该方法将返回整行以及行索引。</p> <p>例如:</p> <pre><code class="language-py">import pandas as pd data = {'Name': ['Tommy', 'Linda', 'Justin', 'Brendon'], 'Age': [21, 19, 20, 18], 'Subject': ['Math', 'Commerce', 'Arts', 'Biology'], 'Scores': [88, 92, 95, 70]} df = pd.DataFrame(data, columns = ['Name', 'Age', 'Subject', 'Scores']) print("The DataFrame is :\n", df) print("\nPerforming Interation using iterrows() method :\n") # iterate through each row and select 'Name' and 'Scores' column respectively. for index, row in df.iterrows(): print (row["Name"], row["Scores"]) </code></pre> <p>输出:</p> <pre><code class="language-py">The DataFrame is : Name Age Subject Scores 0 Tommy 21 Math 88 1 Linda 19 Commerce 92 2 Justin 20 Arts 95 3 Brendon 18 Biology 70 Performing Interation using iterrows() method : Tommy 88 Linda 92 Justin 95 Brendon 70 </code></pre> <h3 id="2使用-itertuples方法">2.使用 itertuples()方法</h3> <p>该方法与 iterrows()方法非常相似,只是它返回命名元组。在元组的帮助下,您可以访问作为属性的特定值,或者换句话说,我们可以访问列中某一行的特定值。这是一种更健壮的方法,并且迭代速度比 iterrows()方法更快。</p> <p>例如:</p> <pre><code class="language-py">import pandas as pd # Creating a dictionary containing students data data = {'Name': ['Tommy', 'Linda', 'Justin', 'Brendon'], 'Age': [21, 19, 20, 18], 'Subject': ['Math', 'Commerce', 'Arts', 'Biology'], 'Scores': [88, 92, 95, 70]} # Converting the dictionary into DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Subject', 'Scores']) print("Given Dataframe :\n", df) print("\n Performing iteration over rows using itertuples() method :\n") # iterate through each row and select 'Name' and 'Scores' column respectively. for row in df.itertuples(index = True, name ='Pandas'): print (getattr(row, "Name"), getattr(row, "Scores")) </code></pre> <p>输出:</p> <pre><code class="language-py">Given Dataframe : Name Age Subject Scores 0 Tommy 21 Math 88 1 Linda 19 Commerce 92 2 Justin 20 Arts 95 3 Brendon 18 Biology 70 Performing iteration over rows using itertuples() method : Tommy 88 Linda 92 Justin 95 Brendon 70 </code></pre> <h3 id="3使用-apply方法">3.使用 apply()方法</h3> <p>这种方法是最有效的方法,比上面两种方法运行时间更快。</p> <p>例如:</p> <pre><code class="language-py">import pandas as pd import pandas as pd # Creating a dictionary containing students data data = {'Name': ['Tommy', 'Linda', 'Justin', 'Brendon'], 'Age': [21, 19, 20, 18], 'Subject': ['Math', 'Commerce', 'Arts', 'Biology'], 'Scores': [88, 92, 95, 70]} # Converting the dictionary into DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Stream', 'Scores']) print("Given Dataframe :\n", df) print("\nPerforming Iteration over rows using apply function :\n") # iterate through each row and concatenate 'Name' and 'Scores' column print(df.apply(lambda row: row["Name"] + " " + str(row["Scores"]), axis = 1)) </code></pre> <p>输出:</p> <pre><code class="language-py">Given Dataframe : Name Age Stream Scores 0 Tommy 21 NaN 88 1 Linda 19 NaN 92 2 Justin 20 NaN 95 3 Brendon 18 NaN 70 Performing Iteration over rows using apply function : 0 Tommy 88 1 Linda 92 2 Justin 95 3 Brendon 70 dtype: object </code></pre> <h3 id="4使用-iloc-功能">4.使用 iloc []功能</h3> <p>这是我们可以用来遍历行的另一个简单函数。我们将在迭代后使用 iloc[]函数选择列的索引。</p> <p>例如:</p> <pre><code class="language-py">import pandas as pd # Creating a dictionary containing students data data = {'Name': ['Tommy', 'Linda', 'Justin', 'Brendon'], 'Age': [21, 19, 20, 18], 'Subject': ['Math', 'Commerce', 'Arts', 'Biology'], 'Scores': [88, 92, 95, 70]} # Converting the dictionary into DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Subject', 'Scores']) print("Given Dataframe :\n", df) print("\nIterating over rows using iloc function :\n") # iterate through each row and select 0th and 3rd index column for i in range(len(df)) : print(df.iloc[i, 0], df.iloc[i, 3]) </code></pre> <p>输出:</p> <pre><code class="language-py">Given Dataframe : Name Age Subject Scores 0 Tommy 21 Math 88 1 Linda 19 Commerce 92 2 Justin 20 Arts 95 3 Brendon 18 Biology 70 Performing Iteration over rows using iloc function : Tommy 88 Linda 92 Justin 95 Brendon 70 </code></pre> <h2 id="结论-80">结论</h2> <p>在本文中,我们学习了在 python 中迭代行的不同方法。iterrows()和 itertuples()方法并不是迭代数据帧行的最有效方法,尽管它们相当简单。为了获得更好的结果和更快的运行时间,您应该寻找 apply()方法。</p> <h1 id="python-中遍历列表的方法">Python 中遍历列表的方法</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/list/iterate-through-list-in-python" target="_blank">https://www.askpython.com/python/list/iterate-through-list-in-python</a></p> </blockquote> <p>在本教程中,我们将学习如何在 Python 中遍历 list。 <a href="https://www.askpython.com/python/list/python-list" target="_blank">Python List</a> 基本上是一个<code>ordered data structure</code>,它使我们能够存储和操作其中的数据。</p> <p>在 Python 中,可以引用以下任何一种方法来迭代列表:</p> <ul> <li><strong>使用 Python range()方法</strong></li> <li><strong>列表理解</strong></li> <li><strong>使用 Python 枚举()方法</strong></li> <li><strong>通过使用 for 循环</strong></li> <li><strong>通过使用 while 循环</strong></li> <li><strong>使用 Python NumPy 模块</strong></li> <li><strong>使用λ函数</strong></li> </ul> <hr> <h2 id="1使用-range方法在-python-中遍历列表">1.使用 range()方法在 Python 中遍历列表</h2> <p>Python 的<code>range()</code>方法可以与 for 循环结合使用,在 Python 中遍历和迭代一个列表。</p> <p>range()方法基本上返回一个<code>sequence of integers</code>,即它从提供的起始索引到参数列表中指定的结束索引构建/生成一个整数序列。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">range (start, stop[, step]) </code></pre> <ul> <li><code>start</code>(上限):该参数用于为将要生成的整数序列提供起始值/索引。</li> <li><code>stop</code>(下限):该参数用于提供要生成的整数序列的结束值/索引。</li> <li><code>step</code>(可选):提供要生成的序列中每个整数之间的差值。</li> </ul> <p><strong>range()函数</strong>生成从起始值到结束/停止值的整数序列,但不包括序列中的结束值,即<strong>不包括结果序列</strong>中的停止号/值。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10, 50, 75, 83, 98, 84, 32] for x in range(len(lst)): print(lst[x]) </code></pre> <p>在上面的代码片段中,使用 range()函数迭代列表,该函数遍历 <strong>0(零)到定义的列表长度</strong>。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">10 50 75 83 98 84 32 </code></pre> <hr> <h2 id="2使用-for-循环遍历-python-中的列表">2.使用 for 循环遍历 Python 中的列表</h2> <p><a href="https://www.askpython.com/python/python-for-loop" target="_blank">Python for loop</a> 可以用来直接遍历列表。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">for var_name in input_list_name: </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10, 50, 75, 83, 98, 84, 32] for x in lst: print(x) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">10 50 75 83 98 84 32 </code></pre> <hr> <h2 id="3列表理解在-python-中遍历列表">3.列表理解在 Python 中遍历列表</h2> <p>Python 列表理解是一种生成具有特定属性或规范的元素列表的不同方式,即它可以识别输入是否是列表、字符串、元组等。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">[expression/statement for item in input_list] </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10, 50, 75, 83, 98, 84, 32] [print(x) for x in lst] </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">10 50 75 83 98 84 32 </code></pre> <hr> <h2 id="4用-while-循环遍历-python-中的列表">4.用 while 循环遍历 Python 中的列表</h2> <p><a href="https://www.askpython.com/python/python-while-loop" target="_blank">Python while 循环</a>也可以用来以类似 for 循环的方式迭代列表。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">while(condition) : Statement update_expression </code></pre> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10, 50, 75, 83, 98, 84, 32] x = 0 # Iterating using while loop while x < len(lst): print(lst[x]) x = x+1 </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">10 50 75 83 98 84 32 </code></pre> <hr> <h2 id="5python-numpy-遍历-python-中的列表">5.Python NumPy 遍历 Python 中的列表</h2> <p><a href="https://www.askpython.com/python-modules/numpy/python-numpy-arrays" target="_blank">Python NumPy 数组</a>也可以用来高效地迭代一个列表。</p> <p>Python numpy.arange()函数创建一个统一的整数序列。</p> <p>【numpy.arange()函数的语法:</p> <pre><code class="language-py">numpy.arange(start, stop, step) </code></pre> <ul> <li><code>start</code>:该参数用于为将要生成的整数序列提供起始值/索引。</li> <li><code>stop</code>:该参数用于提供要生成的整数序列的结束值/索引。</li> <li><code>step</code>:提供待生成序列中每个整数之间的差值。</li> </ul> <p><code>numpy.nditer(numpy_array)</code>是一个为我们提供遍历 NumPy 数组的迭代器的函数。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">import numpy as np n = np.arange(16) for x in np.nditer(n): print(x) </code></pre> <p>在上面的代码片段中, <strong>np.arange(16)</strong> 创建一个从 0 到 15 的整数序列。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 </code></pre> <hr> <h2 id="6python-enumerate方法迭代-python-列表">6.Python enumerate()方法迭代 Python 列表</h2> <p>Python enumerate()函数可用于以优化的方式迭代列表。</p> <p><code>enumerate()</code>函数<strong>将一个计数器添加到列表或任何其他可迭代对象中,并通过函数将其作为枚举对象</strong>返回。</p> <p>因此,<strong>减少了在迭代操作</strong>时保持元素计数的开销。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">enumerate(iterable, start_index) </code></pre> <ul> <li><code>start_index</code>:为迭代 iterable 记录计数器的元素的索引。</li> </ul> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10, 50, 75, 83, 98, 84, 32] for x, res in enumerate(lst): print (x,":",res) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">0 : 10 1 : 50 2 : 75 3 : 83 4 : 98 5 : 84 6 : 32 </code></pre> <hr> <h2 id="7使用-lambda-函数迭代-python-列表">7.使用 lambda 函数迭代 Python 列表</h2> <p>Python 的 lambda 函数基本上都是匿名函数。</p> <p><strong>语法:</strong></p> <pre><code class="language-py">lambda parameters: expression </code></pre> <ul> <li><code>expression</code>:待评估的 iterable。</li> </ul> <p>lambda 函数和 Python map()函数可用于轻松迭代列表。</p> <p>Python <code>map()</code>方法接受一个函数作为参数,并返回一个列表。</p> <p>map()方法的输入函数被 iterable 的每个元素调用,它返回一个新的列表,其中分别包含该函数返回的所有元素。</p> <p><strong>举例:</strong></p> <pre><code class="language-py">lst = [10, 50, 75, 83, 98, 84, 32] res = list(map(lambda x:x, lst)) print(res) </code></pre> <p>在上面的代码片段中, <strong>lambda x:x 函数</strong>作为 map()函数的输入被提供。<strong>lambda x:x 将接受 iterable 的每个元素并返回它</strong>。</p> <p>input_list ( <strong>lst</strong> )作为 map()函数的第二个参数提供。因此,map()函数将把 <strong>lst</strong> 的每个元素传递给 lambda x:x 函数并返回这些元素。</p> <p><strong>输出:</strong></p> <pre><code class="language-py">[10, 50, 75, 83, 98, 84, 32] </code></pre> <hr> <h2 id="结论-81">结论</h2> <p>在这篇文章中。我们已经揭示了迭代 Python 列表的各种技术。</p> <hr> <h2 id="参考-14">参考</h2> <ul> <li>遍历 Python 列表——journal dev</li> </ul> <h1 id="python-版-jupyter-笔记本综合指南">Python 版 Jupyter 笔记本——综合指南</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/jupyter-notebook-for-python" target="_blank">https://www.askpython.com/python/jupyter-notebook-for-python</a></p> </blockquote> <p>在本教程中,我们将了解一个简单但功能强大的 Python 笔记本。我们将学习什么是笔记本,如何安装 Jupyter 笔记本,如何使用它,以及为什么要使用 Jupyter 笔记本。</p> <h2 id="什么是笔记本">什么是笔记本?</h2> <p>要知道什么是笔记本,我们需要知道什么是 REPL。REPL 或读取-评估-打印循环是一种编程环境,顾名思义</p> <ul> <li>它逐行读取编写的代码</li> <li>然后它评估代码</li> <li>查找错误并编译每个块</li> <li>然后将结果(如果有)打印在 REPL shell 上。</li> </ul> <p>这可能看起来很熟悉,因为 Python 就是这样工作的。通常我们使用文本编辑器或 IDE 来编译 Python 代码,但有时对于更简单的计算,Python shell 也能很好地工作。</p> <p>笔记本是增强 REPL 体验的环境。它改善了 REPL 的许多问题,例如:</p> <ul> <li>我们不能撤销写在前面一行的代码</li> <li>编译的代码都不会被保存</li> <li>而且它没有任何编辑特性,比如代码高亮和自动完成。</li> </ul> <h2 id="视觉差异-repl-壳牌-vs-jupyter-笔记本">视觉差异 REPL 壳牌 vs Jupyter 笔记本</h2> <p>让我们看看 REPL shell 和 Jupyter Notebook 上的几个代码块之间的视觉对比。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/b3aa42551d076de52e6efb741bc3595d.png" alt="Python Repl Shell" loading="lazy"></p> <p>Python on the REPL shell</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/159507708053f2b570901af4a452b5a4.png" alt="Python Jupyter Shell" loading="lazy"></p> <p>Python on the Jupyter Notebook</p> <p>从图片中可以清楚地看到 Jupyter Notebook 的功能与 REPL shell 基本相同,但它在许多方面都有所改进。</p> <p>Jupyter Notebook 是一个开源的 web 应用程序,允许您创建和共享包含实时代码、公式、可视化和叙述性文本的文档。</p> <p>引自 Jupyter 官方网站。</p> <p>与文本编辑器不同,Jupyter Notebook 中的代码可以在我们需要的任何时候编译,它会给出我们决定编译的代码块的输出。</p> <p>与 REPL shell 不同,它保存代码和输出,类似于文档。与文档类似,我们可以添加非 Python 文本块,如标题和段落,这些文本块对于理解笔记本中编写的 Python 代码可能有帮助,也可能没有帮助。</p> <p>让我们从使用 Jupyter Notebook 的第一步开始。</p> <h2 id="安装-jupyter-笔记本电脑">安装 Jupyter 笔记本电脑</h2> <p>安装 Jupyter 有两种方法。它与 Anaconda 中的各种其他 Python 工具捆绑在一起,安装 Anaconda 非常简单,但这不在本教程的范围之内。</p> <p>相反,我们将安装 Jupyter Notebook,除了 Python 本身之外没有任何其他软件。让我们开始吧。</p> <h3 id="1安装-python">1.安装 Python</h3> <p>假设你还没有 Python,进入 <a href="https://www.python.org/downloads/" target="_blank">Python 下载</a>,为你的操作系统选择最新稳定版 Python 并下载安装程序,然后在合适的位置安装 Python。</p> <p>要检查您是否已经成功安装了 Python 或者 Python 是否已经安装,请在终端/命令提示符下运行<code>*python*</code>(对于 macOS 为<code>*python3*</code>)。这应该运行 Python 外壳,要退出外壳,只需按 Ctrl + C 或键入<code>*exit()*</code>并回车。</p> <h3 id="2升级-pip-软件包管理器">2.升级 PIP 软件包管理器</h3> <p>这只是为了确保 pip(一个 python 包管理器)正常工作。转到终端/命令提示符并键入:</p> <pre><code class="language-py">python -m pip install --upgrade pip </code></pre> <p>等 pip 最新版本下载安装,现在就可以安装 Jupyter 笔记本了。</p> <h3 id="3安装-jupyter-笔记本">3.安装 Jupyter 笔记本</h3> <p>转到终端/命令提示符并键入:</p> <pre><code class="language-py">python -m pip install notebook </code></pre> <p>等待所有模块下载完毕,现在您应该已经在 PC 上安装了 Jupyter 笔记本电脑。</p> <p>这也应该将 Jupyter Notebook 的路径添加到 Windows 上的环境变量中,这样就可以从终端运行 Jupyter Notebook 了。</p> <h3 id="4运行-jupyter-笔记本">4.运行 Jupyter 笔记本</h3> <p>要运行笔记本,您需要通过终端/命令提示符打开它。去那里输入:</p> <pre><code class="language-py">jupyter notebook </code></pre> <p>这将在您电脑的默认浏览器中打开笔记本。<strong>注意:</strong>你需要一个浏览器来打开笔记本,无论你在哪个浏览器中打开它,它都会作为一个标签运行。</p> <p><strong>注意——一旦关闭终端窗口,进程就会退出。</strong></p> <p>这将在以下位置打开笔记本:<code>C:\Users\<user name></code>,这是您的用户目录。您可以在用户目录中的任何位置打开笔记本,但是您不能离开用户目录。</p> <h3 id="5配置-jupyter-笔记本">5.配置 Jupyter 笔记本</h3> <p>假设您需要在其他位置打开笔记本,我们该如何做呢?</p> <ul> <li>选择需要打开笔记本的位置。确保该位置仅用于 Jupyter,因为名为。ipynb_checkpoints 将在该位置内部创建。但是,如果您不介意该文件夹,您可以选择任何位置。</li> <li>现在打开终端/命令提示符,写:<code>jupyter notebook --notebook-dir "<full location goes here>"</code></li> <li>这将在指定的位置打开笔记本。</li> <li>每次打开笔记本时都这样做是不可行的,所以最好将文本保存在. bat 文件中。每次需要打开 Jupyter Notebook 时运行该文件。</li> </ul> <p>既然我们已经有了 Jupyter Notebook,我们就可以开始使用它了。</p> <h2 id="为-python-使用-jupyter-笔记本">为 Python 使用 Jupyter 笔记本</h2> <p>在开始编写代码之前,我们应该知道如何做一些事情。运行笔记本,尝试以下事情。</p> <h3 id="1创建文件夹">1.创建文件夹</h3> <p>在<em>文件</em>标签下,右上角会有一个名为<em>新建</em>的按钮。点击它,在<em>其他</em>部分下,按下<em>文件夹</em>。</p> <p>目录中会创建一个名为<em>无标题文件夹</em>的文件夹,勾选它旁边的复选框,在<em>文件</em>标签下,点击名为<em>重命名</em>的按钮,输入新名称。(如果需要的话,还可以使用删除按钮。)</p> <p>单击文件夹名称将在同一选项卡中打开该文件夹。</p> <h3 id="2创建-ipython-笔记本">2.创建 iPython 笔记本</h3> <p>点击<em>文件</em>选项卡下的<em>新建</em>按钮,点击<em>笔记本</em>栏目下的 <em>Python 3</em> 。</p> <p>这将在一个新标签页中打开一个名为<em>未命名为</em>的新笔记本,您可能想要更改名称,为此,单击写在页面最上方的名称,系统将提示您编辑它。</p> <h3 id="3编写和运行-python-代码">3.编写和运行 Python 代码</h3> <p>现在我们有了一个笔记本,我们可以开始在里面编写和运行 Python 代码了。一路上,我们会学到几个有用的 Jupyter 笔记本的快捷键。</p> <p>笔记本应该是这样的:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cd1b7baefbe2def153549297baffde75.png" alt="Python Jupyter Notebook" loading="lazy"></p> <p>Jupyter Notebook interface</p> <p>绿色包围的单元格是我们必须写代码的地方,写几行代码,在你认为需要看到输出的地方停下来。</p> <p><strong>现在第一个快捷键来了:<em>Shift+Enter</em>T3。您也可以点击<em>“运行”。</em></strong></p> <p>这将运行您编写的代码,并在单元格下方显示输出。它还将创建一个新的单元格,您可以在其中继续执行剩余的代码。</p> <p>它看起来会像这样:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/11453f62bba2612bda203f574f520988.png" alt="Python Jupyter Cell" loading="lazy"></p> <p>Jupyter Cells</p> <p>请注意,单元格中定义的对象的范围不限于该单元格。这里的变量<code>a</code>和<code>b</code>在定义后可以在笔记本的任何地方使用。</p> <h3 id="4在-jupyter-笔记本中创建降价文档">4.在 Jupyter 笔记本中创建降价文档</h3> <p>笔记本本质上是一个包含所有代码和输出的文档。它还提供了一个附加功能,可以以纯文本形式键入。</p> <p>为此,您需要将单元格设置为“Markdown”而不是“Code”。因此,在命令模式下,按下 <em>m</em> ,你写的任何内容都将被视为纯文本(没有语法高亮显示,并且 <em>shift + enter</em> 只会创建一个新的单元格)。</p> <p>您也可以在上面的下拉菜单中选择<em>“降价”</em>来完成此操作。<br> 在降价模式下按下 <em>y</em> 返回代码。</p> <p>此外,在 markdown 中,您可以添加标题。与惯例类似,标题 1 最大,标题 6 最小。</p> <p>在 Jupyter 笔记本中,在行前键入一个#和一个空格,使其成为 1 级标题,在行前键入两个#和一个空格,使其成为 2 级标题,依此类推。</p> <p>在行前键入 7 个或更多的#和一个空格不会将其转换为任何标题,它将保持为常规纯文本。例如(在降价模式下):</p> <pre><code class="language-py"># Heading 1 ## Heading 2 ### Heading 3 #Not Heading 1 because of no space after the hash </code></pre> <p>请注意,在单元格上按下 <em>Shift + Enter</em> 后,哈希将会消失。输出:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/e5112d2bb414d6883509bff85c6d9334.png" alt="Markdown Code" loading="lazy"></p> <p>Markdown Cell before pressing <em>Shift+Enter</em></p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/7f3e89052001ca2c7e4190d6951b2369.png" alt="Markdown After" loading="lazy"></p> <p>Markdown cell after pressing <em>Shift+Enter</em></p> <p>使用这些工具,您可以编写如下所示的代码:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/1026ee227cffd8ca71e331f90a5d2f17.png" alt="Jupyter Notebook Full Example" loading="lazy"></p> <h2 id="jupyter-笔记本快捷方式">Jupyter 笔记本快捷方式</h2> <ul> <li>按下 <em>Esc</em> 会将上下文移出单元格并进入命令模式。现在,您可以执行与细胞相关的操作。</li> <li>添加单元格“后”:按<em>一</em>(也可以按<em>“+”</em>按钮)</li> <li>在“之前”添加单元格:按下 <em>b</em></li> <li>删除当前选中的单元格:按两次 <em>d</em> (另见<em>“编辑”</em>选项卡)</li> <li>查找和替换:按下 <em>f</em></li> <li>回到编辑模式:按<em>键进入</em></li> </ul> <h2 id="为什么要用-jupyter-笔记本">为什么要用 Jupyter 笔记本?</h2> <p>到目前为止,您可能已经意识到在 Jupyter 笔记本上书写与在文档中记笔记非常相似:</p> <ul> <li>你写代码</li> <li>您还要编写解释代码的文本</li> <li>代码在运行时会提供一个输出</li> <li>所有这些都可以动态改变——这意味着改变代码将会改变输出。</li> </ul> <p>当您再次打开该文件时,它不仅会显示您在所有不同单元格中编写的代码,还会显示您上次关闭笔记本时的输出。</p> <p>可以理解的是,当你要做的编程不是为了创建一个应用程序,而是为了执行和分析数学和/或技术运算时,这是非常有用的。</p> <p>可以说,<a href="https://www.askpython.com/python/examples/roc-curves-machine-learning" target="_blank">机器学习</a>和数据科学是笔记本最大的应用。</p> <p>但是我发现它在几乎每个 Python 程序中都非常有用,在这些程序中,目标是运行程序并查看输出,而不创建任何最终产品。</p> <h2 id="结论-82">结论</h2> <p>在本教程中,我们了解到笔记本基本上是增强的 REPL 外壳,我们了解到如何通过 <a href="https://www.askpython.com/python-modules/python-pip" target="_blank">Python 包管理器 pip</a> 下载并安装 Jupyter Notebook,我们还了解到如何使用笔记本运行 Python 代码。我希望你喜欢阅读本教程。</p> <h1 id="使用-sklearn-在-python-中进行-k-fold-交叉验证">使用 SKLearn 在 Python 中进行 K-Fold 交叉验证</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/k-fold-cross-validation" target="_blank">https://www.askpython.com/python/examples/k-fold-cross-validation</a></p> </blockquote> <p><a href="https://www.askpython.com/python/examples/split-data-training-and-testing-set" target="_blank">将数据集分割成训练集和测试集</a>是让机器学习模型为训练做好准备的一项基本任务。为了确定我们的模型是否过度拟合,我们需要在看不见的数据(验证集)上测试它。</p> <p>如果给定的模型在验证集上表现不佳,那么在处理真实的实时数据时,它的表现会更差。这个概念使得交叉验证可能是机器学习的最重要的概念之一,它确保了我们模型的稳定性。</p> <p>交叉验证只是简单地从数据集中保留一部分数据并用于测试模型(验证集)的方法,保留的数据以外的剩余数据用于训练模型。</p> <p>在本文中,我们将实现 sci-kit learn 提供的交叉验证。我们将实现 K 重交叉验证。</p> <h2 id="交叉验证直觉">交叉验证直觉</h2> <p><strong>我们先来看看为什么要使用交叉验证</strong>。</p> <ul> <li>它帮助我们进行模型评估,最终确定模型的质量。</li> <li>对于确定模型是否能很好地概括数据至关重要。</li> <li>检查模型是否过拟合或欠拟合。</li> <li>最后,它让我们选择具有最佳性能的模型。</li> </ul> <p><strong>交叉验证技术有很多种:</strong></p> <ul> <li>遗漏一个交叉验证</li> <li>k 倍交叉验证</li> <li>分层 k 倍交叉验证</li> <li>时间序列交叉验证</li> </ul> <h2 id="实施-k-倍交叉验证">实施 K 倍交叉验证</h2> <p>数据集被分成“k”个子集,然后 k-1 个子集用于训练模型,最后一个子集作为验证集来测试模型。然后对模型在每个折叠上的得分进行平均,以评估模型的性能。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/3780bb6bdd3a81b4d28536cc62b7c73f.png" alt="5 Fold Cross-Validation" loading="lazy"></p> <p>5 Fold Cross Validation</p> <h2 id="使用-scikit-learn-进行-k-倍交叉验证">使用 scikit learn 进行 k 倍交叉验证</h2> <pre><code class="language-py">#Importing required libraries from sklearn.datasets import load_breast_cancer import pandas as pd from sklearn.model_selection import KFold from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score #Loading the dataset data = load_breast_cancer(as_frame = True) df = data.frame X = df.iloc[:,:-1] y = df.iloc[:,-1] #Implementing cross validation k = 5 kf = KFold(n_splits=k, random_state=None) model = LogisticRegression(solver= 'liblinear') acc_score = [] for train_index , test_index in kf.split(X): X_train , X_test = X.iloc[train_index,:],X.iloc[test_index,:] y_train , y_test = y[train_index] , y[test_index] model.fit(X_train,y_train) pred_values = model.predict(X_test) acc = accuracy_score(pred_values , y_test) acc_score.append(acc) avg_acc_score = sum(acc_score)/k print('accuracy of each fold - {}'.format(acc_score)) print('Avg accuracy : {}'.format(avg_acc_score)) </code></pre> <pre><code class="language-py">accuracy of each fold - [0.9122807017543859, 0.9473684210526315, 0.9736842105263158, 0.9736842105263158, 0.9557522123893806] Avg accuracy : 0.952553951249806 </code></pre> <p>在上面的代码中,我们实现了 5 重交叉验证。</p> <p>sklearn.model_selection 模块为我们提供了 KFold 类,使得交叉验证的实现更加容易。<code>KFold</code>类具有<code>split</code>方法,该方法要求数据集作为输入参数执行交叉验证。</p> <p>我们使用逻辑回归作为我们的模型进行了二元分类,并使用 5 重交叉验证进行了交叉验证。我们的模型的平均准确率约为 95.25%</p> <p>随意查看 Sklearn KFold 文档<a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html" target="_blank">这里</a>。</p> <h2 id="使用-cross_val_score进行交叉验证">使用 cross_val_score()进行交叉验证</h2> <p>您可以使用来自<code>sklearn.model_selection</code>模块的<code>cross_val_score</code>类方法来缩短上述代码。</p> <pre><code class="language-py">from sklearn.datasets import load_breast_cancer import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold data = load_breast_cancer(as_frame = True) df = data.frame X = df.iloc[:,:-1] y = df.iloc[:,-1] k = 5 kf = model_selection.KFold(n_splits=k, random_state=None) model = LogisticRegression(solver= 'liblinear') result = cross_val_score(model , X, y, cv = kf) print("Avg accuracy: {}".format(result.mean())) </code></pre> <pre><code class="language-py">Avg accuracy: 0.952553951249806 </code></pre> <p>来自两个代码的结果是相同的。</p> <p><code>cross_val_score</code>类需要模型、数据集、标签和交叉验证方法作为输入参数。你可以在这里了解更多关于它的功能和方法<a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html" target="_blank">。</a></p> <p>我希望到目前为止,您可能已经了解了交叉验证的概念。</p> <p>使用交叉验证的一个重要实际含义是,随着模型在不同的数据上被训练和测试 k 次,我们将需要更多的计算资源。</p> <h2 id="结论-83">结论</h2> <p>在本文中,我们试图获得交叉验证及其工作背后的一些直觉。我们使用 sklearn 实现了最常用的 K-Fold 交叉验证。</p> <p>快乐学习!</p> <h1 id="在-python-中-k-means-从零开始聚类算法讲解">在 Python 中 K-Means 从零开始聚类[算法讲解]</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/k-means-clustering-from-scratch" target="_blank">https://www.askpython.com/python/examples/k-means-clustering-from-scratch</a></p> </blockquote> <p>K-Means 是一种非常流行的聚类技术。K-means 聚类是另一类非监督学习算法,用于找出给定数据集中的数据聚类。</p> <p>在本文中,我们将使用 <a href="https://www.askpython.com/python-modules/numpy/python-numpy-module" target="_blank">Numpy 模块</a>从头开始实现 K-Means 聚类算法。</p> <h2 id="k-means-聚类算法的-5-个步骤">K-means 聚类算法的 5 个步骤</h2> <p><strong>第一步。随机选取 k 个数据点作为我们的初始质心。</strong></p> <p><strong>第二步。</strong>用 k 个质心找出训练集中每个数据点之间的距离(我们的目的是欧几里德距离)。</p> <p><strong>第三步。</strong>现在根据找到的距离将每个数据点分配到最近的质心。</p> <p><strong>第四步。</strong>通过取每个聚类组中的点的平均值来更新质心位置。</p> <p><strong>第五步。重复步骤 2 到 4,直到我们的质心不变。</strong></p> <p>我们可以使用像肘方法这样的方法来选择 K(聚类数)的最佳值。</p> <h2 id="实现-k-均值聚类算法">实现 K 均值聚类算法</h2> <p>现在让我们用代码实现上面的步骤。导入 numpy 模块,然后浏览这里的其余代码,以了解 K-Means 聚类是如何在代码中实现的。</p> <pre><code class="language-py">#Importing required modules import numpy as np from scipy.spatial.distance import cdist #Function to implement steps given in previous section def kmeans(x,k, no_of_iterations): idx = np.random.choice(len(x), k, replace=False) #Randomly choosing Centroids centroids = x[idx, :] #Step 1 #finding the distance between centroids and all the data points distances = cdist(x, centroids ,'euclidean') #Step 2 #Centroid with the minimum Distance points = np.array([np.argmin(i) for i in distances]) #Step 3 #Repeating the above steps for a defined number of iterations #Step 4 for _ in range(no_of_iterations): centroids = [] for idx in range(k): #Updating Centroids by taking mean of Cluster it belongs to temp_cent = x[points==idx].mean(axis=0) centroids.append(temp_cent) centroids = np.vstack(centroids) #Updated Centroids distances = cdist(x, centroids ,'euclidean') points = np.array([np.argmin(i) for i in distances]) return points </code></pre> <p>上面函数为我们训练集中的每个数据点返回一个聚类标签数组。</p> <h2 id="测试-k-均值聚类">测试 K 均值聚类</h2> <p>我们将使用 digits 数据集(内置在 sklearn 模块中)来测试我们的功能。可以参考<a href="https://www.askpython.com/python/examples/plot-k-means-clusters-python" target="_blank">这篇</a>文章,了解更多绘制 K-Means 聚类的方法。</p> <pre><code class="language-py">#Loading the required modules import numpy as np from scipy.spatial.distance import cdist from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.cluster import KMeans import matplotlib.pyplot as plt #Defining our function def kmeans(x,k, no_of_iterations): idx = np.random.choice(len(x), k, replace=False) #Randomly choosing Centroids centroids = x[idx, :] #Step 1 #finding the distance between centroids and all the data points distances = cdist(x, centroids ,'euclidean') #Step 2 #Centroid with the minimum Distance points = np.array([np.argmin(i) for i in distances]) #Step 3 #Repeating the above steps for a defined number of iterations #Step 4 for _ in range(no_of_iterations): centroids = [] for idx in range(k): #Updating Centroids by taking mean of Cluster it belongs to temp_cent = x[points==idx].mean(axis=0) centroids.append(temp_cent) centroids = np.vstack(centroids) #Updated Centroids distances = cdist(x, centroids ,'euclidean') points = np.array([np.argmin(i) for i in distances]) return points #Load Data data = load_digits().data pca = PCA(2) #Transform the data df = pca.fit_transform(data) #Applying our function label = kmeans(df,10,1000) #Visualize the results u_labels = np.unique(label) for i in u_labels: plt.scatter(df[label == i , 0] , df[label == i , 1] , label = i) plt.legend() plt.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/5b66cb6d22feecd6b65e310d65f8120b.png" alt="Plotting K-Means Clustering" loading="lazy"></p> <p>Plotting K Means Clusters</p> <p>输出结果看起来很有希望。我们的实现是可行的。</p> <h2 id="结论-84">结论</h2> <p>在本文中,我们使用 Python 从头开始创建了一个 K-Means 聚类算法。我们还讲述了制作 K-Means 算法的步骤,最后在 Digits 数据集上测试了我们的实现。你可以在维基百科的<a href="https://en.wikipedia.org/wiki/K-means_clustering" target="_blank">页面上阅读 K-means 聚类算法的理论</a></p> <p>快乐学习</p> <h1 id="用-python-从头开始-k-最近邻">用 Python 从头开始 k-最近邻</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/k-nearest-neighbors-from-scratch" target="_blank">https://www.askpython.com/python/examples/k-nearest-neighbors-from-scratch</a></p> </blockquote> <p>在本文中,我们将学习用 Python 从头开始实现 K 近邻。KNN 是一种监督算法,可用于分类和回归任务。</p> <p>KNN 实现起来非常简单。在本文中,我们将从头开始实现 KNN 算法来执行分类任务。</p> <h2 id="k-最近邻算法背后的直觉">K-最近邻算法背后的直觉</h2> <p>在 K-最近邻中,不需要学习,因为模型存储整个数据集,并基于与之相似的点对数据点进行分类。它仅基于训练数据进行预测。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/9c41779824715d6b3e004e666f4b1e68.png" alt="K-Nearest Neighbors from Scratch Illustration" loading="lazy"></p> <p>KNN Illustration</p> <p>考虑上图。有两类数据(红色和绿色),我们得到了一个新的数据点(黑色),并被要求指定这个新的数据点属于哪个类?</p> <p>KNN 认为相似的物品在群体中更接近。因此很明显,新的数据点更接近红色组,因此该算法将该点分类为红色。你可以在它的 <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm" target="_blank">Wiki 页面</a>上阅读更多关于该算法的信息</p> <p><strong>在 KNN 计算距离的方法</strong>:</p> <ul> <li>曼哈顿方法</li> <li>欧几里德方法</li> <li>闵可夫斯基方法</li> <li>马哈拉诺比斯距离</li> <li>等等..</li> </ul> <p>在本文中,我们将使用欧氏距离来计算新数据点与训练数据集中每个点的接近度。</p> <h2 id="在-python-中从头开始实现-k-近邻">在 Python 中从头开始实现 K 近邻</h2> <p>首先,我们将从头开始计算 K-最近邻的实现步骤。</p> <p><strong>第一步。</strong>找出一个合适的距离度量来计算数据点之间的距离。</p> <p><strong>第二步。</strong>将距离存储在一个数组中,并按照距离的升序进行排序(保留索引,即可以使用 NumPy argsort 方法)。</p> <p><strong>第三步。</strong>选择排序列表中的前 K 个元素。</p> <p><strong>第四步。</strong>执行多数投票,出现次数最多的类别将被指定为待分类数据点的新类别。</p> <h2 id="k-近邻的完整-python-代码">K 近邻的完整 Python 代码</h2> <p>现在在代码中转换上述步骤,从头开始实现我们的 K-最近邻</p> <pre><code class="language-py">#Importing the required modules import numpy as np from scipy.stats import mode #Euclidean Distance def eucledian(p1,p2): dist = np.sqrt(np.sum((p1-p2)**2)) return dist #Function to calculate KNN def predict(x_train, y , x_input, k): op_labels = [] #Loop through the Datapoints to be classified for item in x_input: #Array to store distances point_dist = [] #Loop through each training Data for j in range(len(x_train)): distances = eucledian(np.array(x_train[j,:]) , item) #Calculating the distance point_dist.append(distances) point_dist = np.array(point_dist) #Sorting the array while preserving the index #Keeping the first K datapoints dist = np.argsort(point_dist)[:k] #Labels of the K datapoints from above labels = y[dist] #Majority voting lab = mode(labels) lab = lab.mode[0] op_labels.append(lab) return op_labels </code></pre> <p>我们的预测函数需要一个训练数据集、真实标签、要分类的数据点以及作为输入参数的最近邻数(K)。</p> <h3 id="从虹膜数据集开始的-k-最近邻">从虹膜数据集开始的 k-最近邻</h3> <p>现在是时候在一些数据上测试我们的实现了。</p> <pre><code class="language-py">#Importing the required modules #Importing required modules from sklearn.metrics import accuracy_score from sklearn.datasets import load_iris from numpy.random import randint #Loading the Data iris= load_iris() # Store features matrix in X X= iris.data #Store target vector in y= iris.target #Creating the training Data train_idx = xxx = randint(0,150,100) X_train = X[train_idx] y_train = y[train_idx] #Creating the testing Data test_idx = xxx = randint(0,150,50) #taking 50 random samples X_test = X[test_idx] y_test = y[test_idx] #Applying our function y_pred = predict(X_train,y_train,X_test , 7) #Checking the accuracy accuracy_score(y_test, y_pred) </code></pre> <p><strong>输出:</strong></p> <pre><code class="language-py">0.98 </code></pre> <p>当 K 等于 7 时,我们实现的模型在给定的数据上表现得非常好。</p> <h2 id="结论-85">结论</h2> <p>在本文中,我们从头开始实现了我们自己的 K-最近邻,并将其应用于一个分类问题。</p> <p>我们确定了 KNN 算法的内部工作原理,并研究了制作该算法的步骤。如此简单的 KNN 是机器学习中非常强大和有用的算法。</p> <p>如果您对一些相关的从头实现感兴趣,可以看看这些文章:</p> <ul> <li><a href="https://www.askpython.com/python/examples/logistic-regression-from-scratch" target="_blank">从零开始的逻辑回归</a></li> <li><a href="https://www.askpython.com/python/examples/k-means-clustering-from-scratch" target="_blank">K-Means 聚类算法在 Python 中从头开始</a></li> <li><a href="https://www.askpython.com/python/examples/bag-of-words-model-from-scratch" target="_blank">用 Python 从头开始创建单词包模型</a></li> <li><a href="https://www.askpython.com/python/examples/tf-idf-model-from-scratch" target="_blank">在 Python 中从头开始创建 TF-IDF 模型</a></li> <li><a href="https://www.askpython.com/python/examples/linear-regression-from-scratch" target="_blank">从零开始的线性回归</a></li> </ul> <p>直到我们下次见面。</p> <p>快乐学习!</p> <h1 id="python-中的-keras-深度学习有例子">Python 中的 Keras 深度学习[有例子]</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/keras-deep-learning" target="_blank">https://www.askpython.com/python/examples/keras-deep-learning</a></p> </blockquote> <p>Keras 是一个强大且易于使用的 Python 开源深度学习库。它允许您轻松地建立和训练神经网络和深度学习模型。Keras 也是最受研究人员和开发人员欢迎的深度学习框架之一。Keras 由一个经验丰富的开发人员和贡献者团队开发和维护。Keras 也得到了大量用户和开发者社区的支持。</p> <p>在本文中,我们将讨论以下主题:</p> <ol> <li>Keras 是什么?</li> <li>Keras 的特点</li> <li>Keras 贡献者</li> <li>Keras Models</li> <li>如何使用 Keras?</li> <li>还有更多…</li> </ol> <p>所以让我们开始吧。</p> <h2 id="keras-是什么">Keras 是什么?</h2> <p>Keras 是一个非常流行的深度学习框架,是一个运行在 TensorFlow、Theano 或 CNTK 之上的神经网络 API。</p> <h3 id="keras-的主要特点">Keras 的主要特点</h3> <p>Keras 是一个用于创建深度学习模型的开源库。它是用 Python 编写的,可以运行在 TensorFlow、微软 CNTK 或 Theano 之上。Keras 是一个高级 API,允许开发人员轻松创建深度学习模型。Keras 由世界各地的贡献者积极开发,并在行业中被广泛采用。</p> <p>Keras 是一个高性能的 API,允许轻松创建不同的程序。它专注于用户体验,在行业中被广泛采用。Keras 提供快速原型制作,并在 CPU 和 GPU 上无缝运行。它支持 NVIDeA 和 AMD。Keras 允许自由设计任何架构,并且易于上手。Keras 还为模型提供了简单的制作方法。</p> <h3 id="keras-的贡献者">Keras 的贡献者</h3> <p>在最初阶段,Keras 有将近 48 个以上的贡献者。</p> <p>现在是近 25 万开发者或贡献者。每年都以 2 倍的速度增长。负责 Keras 框架开发的一些顶级公司有微软、谷歌、英伟达和 AWS。一些使用 Keras 框架的流行平台有网飞、优步、谷歌、Instamert 和华为。</p> <h3 id="keras-上的用户体验">Keras 上的用户体验</h3> <ul> <li><strong>用户友好的 API</strong> <ul> <li>Keras 是为人类设计的 API。</li> <li>它遵循最佳实践来减少认知负荷。</li> <li>它遵循一致性和简单的 API。</li> </ul> </li> <li><strong>不是为机器设计的</strong> <ul> <li>Keras 对用户造成的任何错误提供了明确的反馈。</li> <li>这最大限度地减少了常见用例所需的用户操作数量。</li> </ul> </li> <li><strong>易学易用</strong> <ul> <li>它是非常多产的。</li> <li>它提供了比你想象的更多的想法。</li> <li>这有助于持续获胜,并为赢得比赛提供最佳支持。</li> </ul> </li> <li><strong>高灵活性</strong> <ul> <li>它通过集成其他深度学习语言,如 TensorFlow 和 Theranos,为所有开发人员提供了更高的灵活性。</li> <li>你可以用 basic 语言实现任何东西。</li> </ul> </li> </ul> <h3 id="多后端和多平台战略">多后端和多平台战略</h3> <p>Keras 提供了多后端以及多平台的工作策略,这样代码就可以聚集在一起完成相同的任务。</p> <ul> <li>我们可以用 python 和 R 开发 Keras。</li> <li>我们可以使用以下后端引擎运行代码: <ul> <li>TensorFlow</li> <li>提亚诺</li> </ul> </li> <li>它提供了将网络计算部署到多个 CPU 和 GPU 服务器的灵活性。</li> <li>它使用以下方式生成模型: <ul> <li>TF-服务</li> <li>GPU 加速</li> <li>安卓(TF,TF lite)</li> <li>iOS(原生 coreML)</li> <li>树莓派</li> </ul> </li> </ul> <h2 id="什么是-keras-车型">什么是 Keras 车型?</h2> <p>Kers 用于构建不同的机器学习模型。Keras 的模型也提供了一些简单的工作方法。基本上,我们也将讨论两种不同的 Keras 模型。</p> <ul> <li>顺序模型</li> <li>功能模型</li> </ul> <h3 id="1顺序模型">1.顺序模型</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/6013f3357ec74f3322be4ec22419e7b8.png" alt="Sequential Model " loading="lazy"></p> <p>Sequential Model</p> <p><strong>Keras 顺序 API 模型的特点</strong></p> <ul> <li>它的工作原理类似于线性层叠。</li> <li>这对于创建示例模型非常有用,例如: <ul> <li>网络的简单分类</li> <li>编码器-解码器模型</li> </ul> </li> <li>该模型将每一层视为一个对象,为同一模型中的下一层提供信息。</li> <li>这个系统被称为顺序模型。</li> </ul> <h3 id="2功能模型">2.功能模型</h3> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/cd965ae142b4fe373782be13597c7743.png" alt="Functional Model" loading="lazy"></p> <p>Functional Model</p> <p><strong>功能 API 模型的特点</strong></p> <ul> <li>该模型具有多输入、多输出和任意静态图拓扑。</li> <li>它提供了复杂的模型,这些模型可以分成两个或更多的分支或共享层。</li> <li>功能域中使用的概念称为域适应。</li> </ul> <h2 id="在-keras-api-框架中执行">在 Keras API 框架中执行</h2> <p><strong>对于在 Keras API 框架中创建的模型,可能有两种不同类型的执行,如下:</strong></p> <ul> <li><strong>符号执行</strong> <ul> <li>在这种类型的执行中,我们首先构建一个计算图。</li> <li>然后编译好的图就在后面执行了。</li> <li>它在 python 代码中有价值。</li> </ul> </li> <li><strong>急切(迫切)执行</strong> <ul> <li>在这种类型的执行过程中,python 运行时就是执行运行时。</li> <li>这类似于用 NumPy 执行。</li> <li>它在 python 代码中没有值。</li> <li>对于急切执行,可以使用值相关的动态拓扑(树形 rnn)。</li> </ul> </li> </ul> <h2 id="使用-keras-的实例">使用 Keras 的实例</h2> <p>我们将学习如何使用 Keras API,然后是一个示例程序。跟随代码片段。首先,让我们在命令提示符下使用 <strong><a href="https://www.askpython.com/python-modules/python-pip" target="_blank">Pip 安装程序</a>安装 Keras 库。</strong></p> <pre><code class="language-py">#installing keras using pip installer pip install keras Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/ Requirement already satisfied: keras in /usr/local/lib/python3.7/dist-packages (2.9.0) </code></pre> <p>在我们的示例程序中,我们将加载一个预加载的数据集,Keras API 的 <a href="https://www.askpython.com/python/examples/load-and-plot-mnist-dataset-in-python" target="_blank"><strong>MNIST 数据集</strong></a> ,并使用 Keras 方法打印它。然后,我们将使用 Keras 实用程序对数据集中的输入数据进行规范化。</p> <p>Keras API 中提供的一些其他预加载数据集是波士顿住房数据集、cifar 10(10 个图像标签的分类)数据集和 IMDB 电影评论数据集。MNIST 数据集是 Keras API 中预加载的数据集。</p> <p>在我们获取的数据集中,有 10 条数据。我们不是处理所有的数据,而是只取两个数据并打印出来,然后处理它们。它可以通过下面的代码获得。</p> <pre><code class="language-py">from keras.datasets import mnist #loading datas in variables (x_train, y_train), (x_test, y_test) = mnist.load_data() #we will print 1st two datas from the dataset using the following code from matplotlib import pyplot for i in range(2): pyplot.imshow(x_train[i], cmap=pyplot.get_cmap('gray')) pyplot.show() </code></pre> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/82c666a7fb4d6bae5422175f81cd6592.png" alt="" loading="lazy"></p> <p>我们可以通过使用区间[0,1]将输入值从类型 unit8 缩放到 float32 来规范化数据集中的数据。这将允许任何值的概率落在 0 到 1 的范围内。</p> <pre><code class="language-py">x_train = x_train.astype(‘float32’) x_test = x_test.astype(‘float32’) x_train /= 255 x_test /= 255 </code></pre> <p>由于我们要将数据从二维数组缩放到单个向量,我们需要使用以下代码片段将 28*28 数组的 MNIST 数据集的每个图像转换为具有 784(28 * 28 = 784)个分量的向量:</p> <pre><code class="language-py">x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) </code></pre> <p>对于我们数据集中的每个图像,对应于该图像有一个介于 0 和 9 之间的级别。我们需要用一个包含 10 个位置的向量来表示这些信息,在对应于表示图像的数字的位置用 1 表示,在所有其他位置用 0 表示。我们可以使用<code>keras.util</code>中的 to _ categorical()方法来实现这一点。</p> <pre><code class="language-py">from keras.utils import to_categorical y_train = to_categorical(y_train, num_classes=10) y_test = to_categorical(y_test, num_classes=10) </code></pre> <pre><code class="language-py">#Now printing our final normalized data from our datasets print(y_test[4]) print(y_train[5]) print(y_train.shape) print(y_test.shape) </code></pre> <p>因此,我们得到了数据集中数据(图像)的归一化值。我们在最后一行中打印了同样的内容,得到的输出如下。</p> <pre><code class="language-py">[[0\. 0\. 0\. ... 1\. 0\. 0.] [0\. 0\. 1\. ... 0\. 0\. 0.] [0\. 1\. 0\. ... 0\. 0\. 0.] ... [0\. 0\. 0\. ... 0\. 0\. 0.] [0\. 0\. 0\. ... 0\. 0\. 0.] [0\. 0\. 0\. ... 0\. 0\. 0.]] [[0\. 0\. 0\. ... 0\. 0\. 0.] [1\. 0\. 0\. ... 0\. 0\. 0.] [0\. 0\. 0\. ... 0\. 0\. 0.] ... [0\. 0\. 0\. ... 0\. 0\. 0.] [0\. 0\. 0\. ... 0\. 0\. 0.] [0\. 0\. 0\. ... 0\. 1\. 0.]] (60000, 10) (10000, 10) </code></pre> <p>通过这种方式,我们在 Keras 数据框中使用了预加载的数据集,并对数据集中的所有输入数据(影像)进行了归一化处理。</p> <h2 id="结论-86">结论</h2> <p>今天我们学习了 Keras API 框架及其不同的特性。虽然它主要是理论上的,我们希望你喜欢它。我们将带着更多激动人心的话题再次访问。</p> <h1 id="用-python-实现键盘记录器">用 Python 实现键盘记录器</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/keylogger-in-python" target="_blank">https://www.askpython.com/python/examples/keylogger-in-python</a></p> </blockquote> <p>大家好!在今天的帖子中,我们将做一些令人兴奋的事情——用 Python 构建一个键盘记录器!</p> <p>你有没有想过监控你的键盘,看看你的打字历史,并分析你如何打字?好吧,第一步是建立一个键盘监控工具——或者一个<strong>键盘记录器</strong>!</p> <p>虽然您很可能意识到这可能会被恶意使用,但我们假设您是控制自己机器的人!</p> <p>我们开始吧!</p> <hr> <h2 id="安装必要的模块">安装必要的模块</h2> <p>第一步是确保你有合适的工具!除了 Python 3,你还必须安装 <a href="https://pynput.readthedocs.io/en/latest/" target="_blank"><strong>pynput</strong> 模块</a>,以便从你的键盘读取输入。让我们使用 <a href="https://www.askpython.com/python-modules/python-pip" target="_blank">pip 安装命令</a>。</p> <pre><code class="language-py">pip install pynput </code></pre> <p>虽然我们也可以控制键盘,但我们只是监视和记录在键盘上输入的内容!</p> <p>这个模块只是使用一个后端引擎,根据你的操作系统来监控你的键盘。例如,如果你使用 Linux,你可能有一个<code>xorg</code>服务器,你可以用它作为后端。</p> <p>这个模块与后端引擎交互,从键盘获取输入。</p> <p>管道如下图所示:</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/fc30ef308e70090345fea65c9a941d50.png" alt="Pipeline Keylogger" loading="lazy"></p> <p>Pipeline Keylogger</p> <p>因此,这个模块将跨不同的操作系统工作,因为它完成了处理后端调用的所有工作!</p> <p>我们将使用 Python 设计以下键盘记录器:</p> <ul> <li>我们创建一个主循环,简单地等待一个键被按下。</li> <li>一旦监听器检测到按键,我们将在控制台上打印出来。</li> </ul> <p>让我们现在开始写代码。</p> <h2 id="用-python-实现键盘记录器-1">用 Python 实现键盘记录器</h2> <p>我们将用 Python 编写一个键盘记录器,它使用了<code>pynput.keyboard</code>类。</p> <p>让我们先做必要的进口</p> <pre><code class="language-py">import pynput.keyboard as Keyboard </code></pre> <p>现在,我们将监听键盘,我们将监视两种事件:</p> <ul> <li>按键——每当按键时</li> <li>按键释放–每当按键被释放时</li> </ul> <p>现在,<code>pynput</code>已经让我们的生活变得非常容易。我们只需要定义两个函数来处理按键被按下和释放时的逻辑。</p> <p>我们只需要定义这些函数,并使用<code>pynput</code>将它们作为参数传递给键盘监听器。</p> <p>创建侦听器的格式如下:</p> <pre><code class="language-py">with Keyboard.Listener(on_press=on_press, on_release=on_release) as listener: listener.join() </code></pre> <p>只是两行代码而已!这里有两个回调函数<code>on_press()</code>和<code>on_release()</code>,它们将被相应地调用。</p> <p>第二行使用<code>Threading.join()</code>方法简单地等待监听器线程完成执行。</p> <p>现在让我们也来定义这两个函数。</p> <pre><code class="language-py">def on_press(key): # Callback function whenever a key is pressed try: print(f'Key {key.char} pressed!') except AttributeError: print(f'Special Key {key} pressed!') def on_release(key): print(f'Key {key} released') if key == Keyboard.Key.esc: # Stop the listener return False </code></pre> <p>这里,我们首先打印使用<code>key.char</code>按下/释放的任何键。</p> <p>如果按下一个特殊的键,我们必须打印出<code>key</code>,因为<code>key.char</code>不是一个有效的 ASCII 值。</p> <p>同样,我们对<code>on_release(key)</code>做同样的事情,直到< Esc >键被按下。</p> <p>我们简单地返回<code>False</code>,这将<strong>自动停止</strong>监听器并完成我们的程序!</p> <p>以下是到目前为止的完整程序:</p> <pre><code class="language-py">import pynput.keyboard as Keyboard def on_press(key): # Callback function whenever a key is pressed try: print(f'Key {key.char} pressed!') except AttributeError: print(f'Special Key {key} pressed!') def on_release(key): print(f'Key {key} released') if key == Keyboard.Key.esc: # Stop the listener return False with Keyboard.Listener(on_press=on_press, on_release=on_release) as listener: listener.join() </code></pre> <p><strong>样本输出</strong></p> <pre><code class="language-py">Key q pressed! Key 'q' released Key w pressed! Key 'w' released Special Key Key.shift pressed! Key A pressed! Key 'A' released Key Key.shift released Key a pressed! Key 'a' released Special Key Key.shift pressed! Key A pressed! Key 'A' released Key Key.shift released Special Key Key.shift pressed! Key @ pressed! Key '@' released Key Key.shift released Special Key Key.shift pressed! Key $ pressed! Key '$' released Key Key.shift released Special Key Key.shift pressed! Key ) pressed! Key ')' released Key Key.shift released Special Key Key.shift pressed! Key > pressed! Key '>' released Key Key.shift released Key . pressed! Key '.' released Special Key Key.esc pressed! Key Key.esc released </code></pre> <p>正如你所看到的,这是能够成功地捕捉和打印键盘输出,甚至与特殊的关键,如<code><shift></code>!</p> <hr> <h2 id="结论-87">结论</h2> <p>希望,你现在能够让你的键盘记录器轻松工作!你也可以在此基础上为你的键盘记录程序实现更多的功能。下次见!</p> <hr> <h2 id="参考-15">参考</h2> <ul> <li><a href="https://pynput.readthedocs.io/en/latest/keyboard.html" target="_blank">pynput 模块</a>文档</li> </ul> <hr> <h1 id="用-python-动态规划求解-01-背包">用 Python 动态规划求解 0/1 背包</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/knapsack-problem-dynamic-programming" target="_blank">https://www.askpython.com/python/examples/knapsack-problem-dynamic-programming</a></p> </blockquote> <p>在本文中,我们将使用动态规划来解决 0/1 背包问题。</p> <p><em><strong>动态规划</strong>是一种算法技术,通过将其分解为更简单的子问题,并利用整体问题的最优解取决于其子问题的最优解的事实来解决优化问题</em> <strong>。</strong></p> <p><strong>0/1 背包</strong>也许是动态规划下最流行的问题。为了掌握动态编程的诀窍,学习起来也是一个很大的问题。</p> <p>在本教程中,我们将学习什么是 0/1 背包,以及如何使用动态编程在 Python 中解决它。</p> <p>让我们开始吧。</p> <h2 id="01-背包的问题陈述">0/1 背包的问题陈述</h2> <p>动态编程的问题陈述如下:</p> <pre><code class="language-py">Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. </code></pre> <p>首先,我们有一个权重数组,其中包含所有项目的权重。我们还有一个值数组,其中包含所有物品的值,我们还有一个背包的总重量。</p> <p>根据这些信息,我们需要找到在重量限制范围内可以获得的最大值。</p> <p>这个问题被称为 0/1 背包,因为我们既可以把一个项目作为一个整体包含进去,也可以把它排除在外。也就是说,我们不能拿一个项目的零头。</p> <p>我们举个例子来了解一下。</p> <p>取以下输入值。</p> <pre><code class="language-py">val = [50,100,150,200] wt = [8,16,32,40] W = 64 </code></pre> <p>在这里,当我们包括项目 <strong>1、2 和 4</strong> 时,我们得到最大利润,总共得到 <strong>200 + 50 + 100 = 350。</strong></p> <p>因此,总利润为:</p> <pre><code class="language-py">350 </code></pre> <h2 id="如何用动态规划求解-01-背包">如何用动态规划求解 0/1 背包?</h2> <p>为了使用动态规划解决 0/1 背包问题,我们构建了一个具有以下维度的表。</p> <pre><code class="language-py">[n + 1][W + 1] </code></pre> <p>表格的行对应于从 <strong>0 到 n</strong> 的项目。</p> <p>表中的列对应于从 <strong>0 到 W.</strong> 的重量限制</p> <p>表格最后一个单元格的索引是:</p> <pre><code class="language-py">[n][W] </code></pre> <p>索引为[i][j]的单元格的值表示当考虑从 0 到 I 的项目并且总重量限制为 j 时可能的最大利润。</p> <p>填完表格后,我们的答案会在表格的最后一个单元格中。</p> <h3 id="怎么填表">怎么填表?</h3> <p>让我们从将第 0 行和第 0 列设置为 0 开始。我们这样做是因为第 0 行意味着我们没有对象,第 0 列意味着可能的最大权重是 0。</p> <p>现在对于每个单元格[i][j],我们有两个选项:</p> <ol> <li>要么我们在最终选择中包含对象[i]。</li> <li>或者我们在最终选择中不包括对象[i]。</li> </ol> <p>我们如何决定是否在选择中包含对象[i]?</p> <p>包含对象[i]需要满足两个条件:</p> <ol> <li>包括物体[i]后的总重量<strong>不应超过</strong>的<strong>重量限制。</strong></li> <li>包括对象[i]后的<strong>利润</strong>应该比不包括对象时的<strong>大</strong>。</li> </ol> <p>让我们把对 0/1 背包的理解转换成 python 代码。</p> <h2 id="求解-01-背包的-python-代码">求解 0/1 背包的 Python 代码</h2> <p>让我们使用下面的<a href="https://www.askpython.com/python/list/python-list-comprehension" target="_blank">列表理解方法</a>创建一个表格:</p> <pre><code class="language-py">table = [[0 for x in range(W + 1)] for x in range(n + 1)] </code></pre> <p>我们将使用嵌套的 <a href="https://www.askpython.com/python/python-for-loop" target="_blank">for 循环</a>遍历表格并填充每个单元格中的条目。</p> <p>我们将以自下而上的方式填充表格。</p> <pre><code class="language-py">for i in range(n + 1): for j in range(W + 1): if i == 0 or j == 0: table[i][j] = 0 elif wt[i-1] <= j: table[i][j] = max(val[i-1] + table[i-1][j-wt[i-1]], table[i-1][j]) else: table[i][j] = table[i-1][j] </code></pre> <p>让我们一行一行地分解代码。</p> <pre><code class="language-py"> if i == 0 or j == 0: table[i][j] = 0 </code></pre> <p>这部分代码负责将第 0 行和第 0 列设置为 0。</p> <pre><code class="language-py"> elif wt[i-1] <= j: </code></pre> <p>这行代码检查第 I 个对象的重量是否小于该单元格(j)允许的总重量。</p> <pre><code class="language-py"> table[i][j] = max(val[i-1] + table[i-1][j-wt[i-1]], table[i-1][j]) </code></pre> <p>这行代码负责从我们可用的两个选项中选择最大值。我们可以包含该对象,也可以排除它。</p> <p>这里的术语<strong>table[I–1][j]</strong>表示不包括第 I 项。术语<strong>val[I–1]+table[I–1][j–wt[I–1]]</strong>表示包含第 I 项。</p> <pre><code class="language-py">else: table[i][j] = table[i-1][j] </code></pre> <p>当第 I 个物体的重量大于允许极限(j)时,进入循环的这一部分。</p> <p>当我们完成填充表格时,我们可以返回表格的最后一个单元格作为答案。</p> <pre><code class="language-py">return table[n][W] </code></pre> <h3 id="背包求解函数的完整代码">背包求解函数的完整代码</h3> <p>求解背包问题的函数的完整代码如下所示:</p> <pre><code class="language-py">def knapSack(W, wt, val): n=len(val) table = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(n + 1): for j in range(W + 1): if i == 0 or j == 0: table[i][j] = 0 elif wt[i-1] <= j: table[i][j] = max(val[i-1] + table[i-1][j-wt[i-1]], table[i-1][j]) else: table[i][j] = table[i-1][j] return table[n][W] </code></pre> <p>让我们试着运行上面例子中的函数。</p> <pre><code class="language-py">val = [50,100,150,200] wt = [8,16,32,40] W = 64 print(knapSack(W, wt, val)) </code></pre> <h2 id="完全码-2">完全码</h2> <p>这是在您的系统上运行的完整代码。</p> <pre><code class="language-py">def knapSack(W, wt, val): n=len(val) table = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(n + 1): for j in range(W + 1): if i == 0 or j == 0: table[i][j] = 0 elif wt[i-1] <= j: table[i][j] = max(val[i-1] + table[i-1][j-wt[i-1]], table[i-1][j]) else: table[i][j] = table[i-1][j] return table[n][W] val = [50,100,150,200] wt = [8,16,32,40] W = 64 print(knapSack(W, wt, val)) </code></pre> <p>运行代码后,我们得到以下输出:</p> <pre><code class="language-py">350 </code></pre> <h2 id="结论-88">结论</h2> <p>本教程是关于用 Python 动态编程解决 0/1 背包问题的。我们希望你和我们一起学习愉快!</p> <h1 id="利用递归在-python-中求解-0-1-背包问题">利用递归在 Python 中求解 0-1 背包问题</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/knapsack-problem-recursion" target="_blank">https://www.askpython.com/python/examples/knapsack-problem-recursion</a></p> </blockquote> <p>嗨伙计们!在本教程中,我试图解释背包问题。在面试过程中,你会在某个地方遇到这个问题。</p> <p>为了解决这个问题,我们将使用递归方法。如果你不知道递归是如何工作的,看看下面的教程。</p> <p><em><strong>了解更多关于递归的知识:<a href="https://www.askpython.com/python/python-recursion-function" target="_blank">Python 中的递归</a></strong></em></p> <hr> <h2 id="背包问题简介">背包问题简介</h2> <p>有个小偷带着一个能装下总重量<code>capacity</code>的背包。他有 n 件不同重量和价格的物品要偷。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/449ea20180ad21797760b2222a2436ce.png" alt="01 Knapsack Problem" loading="lazy"></p> <p>01 Knapsack Problem</p> <p>我们的目标是创建一个名为<code>**knapsack**</code>的函数,它将找出这些物品的子集,考虑到所有物品的总重量不超过背包的给定<code>capacity</code>,从而为小偷带来最大利润。</p> <p><em><strong>也读:<a href="https://www.askpython.com/python/examples/friends-travel-problem" target="_blank">用 Python 解决朋友旅行问题【谷歌面试问题】</a></strong></em></p> <p>下图说明了同样的情况。</p> <p><img src="https://github.com/OpenDocCN/geekdoc-python-zh/raw/master/askpython/img/40039ea8666d3aa1b40fb50aa9d3cfdc.png" alt="01 Knapsack Problem 1" loading="lazy"></p> <p>01 Knapsack Problem 1</p> <hr> <h2 id="用递归解决-python-中的背包问题">用递归解决 Python 中的背包问题</h2> <p>我们将考虑到,对于每一件物品,小偷有两种选择:要么包括该物品,要么排除该物品,不要拿起它。</p> <p>如果小偷<strong>包括一个物品,</strong>我们将为剩余的 <strong>n-1</strong> 物品寻找最大利润,并且也将根据所包括物品的重量减少容量。</p> <p>总利润,在这种情况下,将是:<strong>物品价格+n-1 个物品的利润(容量-物品重量)剩余</strong></p> <p>如果一个人排除了该商品,我们将从商店中找到剩余的 <strong>n-1</strong> 商品的利润。在这种情况下,利润将是:<strong>剩余产能的 n-1 项利润</strong></p> <p>最终答案将是两种情况下的最大利润。</p> <hr> <h2 id="代码实现-1">代码实现</h2> <pre><code class="language-py">def knapsack(n,capacity,weights,prices): if(n==0 or capacity==0): return 0 if (weights[n-1]>capacity): return knapsack(n-1,capacity,weights,prices) else: return max(prices[n-1] + knapsack(n-1,capacity-weights[n-1],weights,prices), knapsack(n-1,capacity,weights,prices)) weights = [1,2,3,4] prices = [50,200,150,100] n = 4 capacity = 7 print(knapsack(n,capacity,weights,prices)) </code></pre> <p>当前代码执行后接收到的输出为 <strong>400</strong> ,这是正确的输出。</p> <hr> <p>感谢您花时间阅读教程!我希望背包问题现在你已经清楚了。</p> <p>快乐学习!😇</p> <hr> <h1 id="python-中的-knn简单实用的实现">Python 中的 KNN——简单实用的实现</h1> <blockquote> <p>原文:<a href="https://www.askpython.com/python/examples/knn-in-python" target="_blank">https://www.askpython.com/python/examples/knn-in-python</a></p> </blockquote> <p>读者朋友们,你们好!在这篇文章中,我们将关注对 Python 中 KNN 的<strong>理解和实现。</strong></p> <p>所以,让我们开始吧!!</p> <hr> <h2 id="什么是-knn-算法">什么是 KNN 算法?</h2> <p>KNN 是 K 近邻的首字母缩写。它是一种有监督的机器学习算法。KNN 基本上用于分类和回归。</p> <p>KNN 不假设任何底层参数,即它是一个<code>non-parametric</code>算法。</p> <hr> <h3 id="knn-算法遵循的步骤">KNN 算法遵循的步骤</h3> <ul> <li>它最初将训练数据存储到环境中。</li> <li>当我们提出用于预测的数据时,Knn 根据训练数据集为新的测试记录选择 <strong>k 个最相似/相似的数据值</strong>。</li> <li>此外,使用<code>Euclidean or Manhattan distance</code>为新测试点选择 k 个最相似的邻居。基本上,他们计算测试点和训练数据值之间的距离,然后选择 K 个最近的邻居。</li> <li>最后,将测试数据值分配给包含测试数据的 K 个最近邻的最大点的类或组。</li> </ul> <hr> <h3 id="k-nn-的真实例子">K-NN 的真实例子</h3> <p><strong>问题陈述—</strong>考虑一袋珠子(训练数据),有两种颜色——绿色和蓝色。</p> <p>所以,这里有两类:绿色和蓝色。我们的任务是找到一个新的珠子“Z”会落在哪个类中。</p> <p><strong>解决方案—</strong>最初,我们随机选择 K 的值。现在假设 K=4。因此,KNN 将使用所有训练数据值(一袋珠子)计算 Z 的距离。</p> <p>此外,我们选择最接近 Z 的 4(K)个值,然后尝试分析 4 个邻居中的大多数属于哪个类。</p> <p>最后,Z 被分配一类空间中的大多数邻居。</p> <hr> <h2 id="knn-在-python-中的实现">KNN 在 Python 中的实现</h2> <p>现在,让我们试着用 KNN 的概念来解决下面的回归问题。</p> <p>我们得到了一个数据集,其中包含了根据各种环境条件选择租赁自行车的人数的历史数据。</p> <p>你可以在这里找到数据集<a href="https://github.com/Safa1615/BIKE-RENTAL-COUNT/blob/master/day.csv" target="_blank">。</a></p> <p>所以,让我们开始吧!</p> <hr> <h3 id="1加载数据集">1.加载数据集</h3> <p>我们已经利用 <a href="https://www.askpython.com/python-modules/pandas/python-pandas-module-tutorial" target="_blank">Pandas 模块</a>将数据集加载到使用<code>pandas.read_csv()</code>函数的环境中。</p> <pre><code class="language-py">import pandas BIKE = pandas.read_csv("Bike.csv") </code></pre> <h3 id="2选择正确的功能">2.选择正确的功能</h3> <p>我们利用<a href="https://www.askpython.com/python/examples/correlation-matrix-in-python" target="_blank">相关回归分析</a>技术从数据集中选择重要变量。</p> <pre><code class="language-py">corr_matrix = BIKE.loc[:,numeric_col].corr() print(corr_matrix) </code></pre> <p><strong>相关矩阵</strong></p> <pre><code class="language-py"> temp atemp hum windspeed temp 1.000000 0.991738 0.114191 -0.140169 atemp 0.991738 1.000000 0.126587 -0.166038 hum 0.114191 0.126587 1.000000 -0.204496 windspeed -0.140169 -0.166038 -0.204496 1.000000 </code></pre> <p>由于“temp”和“atemp”高度相关,我们从数据集中删除了“atemp”。</p> <pre><code class="language-py">BIKE = BIKE.drop(['atemp'],axis=1) </code></pre> <h3 id="3分割数据集">3.分割数据集</h3> <p>我们已经利用 <a href="https://www.askpython.com/python/examples/split-data-training-and-testing-set" target="_blank">train_test_split()函数</a>将数据集分成 80%的训练数据集和 20%的测试数据集。</p> <pre><code class="language-py">#Separating the dependent and independent data variables into two data frames. from sklearn.model_selection import train_test_split X = bike.drop(['cnt'],axis=1) Y = bike['cnt'] # Splitting the dataset into 80% training data and 20% testing data. X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.20, random_state=0) </code></pre> <h3 id="4定义误差指标">4.定义误差指标</h3> <p>由于这是一个回归问题,我们将 <a href="https://www.askpython.com/python/examples/mape-mean-absolute-percentage-error?_thumbnail_id=9324" target="_blank">MAPE</a> 定义为如下所示的误差指标</p> <pre><code class="language-py">import numpy as np def MAPE(Y_actual,Y_Predicted): mape = np.mean(np.abs((Y_actual - Y_Predicted)/Y_actual))*100 return Mape </code></pre> <h3 id="5建立模型">5.建立模型</h3> <p><code>sklearn.neighbors module</code>包含实现 Knn 的<code>KNeighborsRegressor()</code>方法,如下所示</p> <pre><code class="language-py">#Building the KNN Model on our dataset from sklearn.neighbors import KNeighborsRegressor KNN_model = KNeighborsRegressor(n_neighbors=3).fit(X_train,Y_train) </code></pre> <p>此外,我们使用 <a href="https://www.askpython.com/python/examples/python-predict-function" target="_blank">predict()函数</a>来预测测试数据。</p> <pre><code class="language-py">KNN_predict = KNN_model.predict(X_test) #Predictions on Testing data </code></pre> <h3 id="6准确性检查">6.准确性检查!</h3> <p>我们调用上面定义的 MAPE 函数来检查分类错误并判断模型预测的准确性。</p> <pre><code class="language-py"># Using MAPE error metrics to check for the error rate and accuracy level KNN_MAPE = MAPE(Y_test,KNN_predict) Accuracy_KNN = 100 - KNN_MAPE print("MAPE: ",KNN_MAPE) print('Accuracy of KNN model: {:0.2f}%.'.format(Accuracy_KNN)) </code></pre> <p><strong>Knn 的精度评估—</strong></p> <pre><code class="language-py">MAPE: 17.443668778014253 Accuracy of KNN model: 82.56%. </code></pre> <hr> <h2 id="结论-89">结论</h2> <p>到此,我们就结束了这个话题。如果你遇到任何问题,欢迎在下面评论。</p> <p>更多与 Python 相关的帖子,敬请关注,在此之前,祝你学习愉快!!🙂</p>

posted @ 2024-10-31 16:48  绝不原创的飞龙  阅读(10)  评论(0)    收藏  举报