PythonForBeginners-中文系列教程-二-
PythonForBeginners 中文系列教程(二)
检测无向图中的圈
原文:https://www.pythonforbeginners.com/basics/detect-cycle-in-an-undirected-graph
图形遍历算法用于在图形数据结构上执行各种操作。在本文中,我们将使用广度优先图遍历算法来检测无向图中的循环。
什么是图中的循环?
我们说一个圈存在于一个图中,如果我们从一个顶点出发,只穿过一条或多条边一次,就能到达同一个地方。换句话说,如果我们可以从一个顶点出发,只穿过一条或多条边一次就到达同一个顶点,那么我们说图中存在一个圈。
例如,考虑下图。

Graph in Python
在这个图中,我们可以从顶点 A 出发,穿过边 E₂->E₅->E₄后到达同一个顶点。所以,我们会说在图中存在一个循环。
我们也可以从顶点 B 开始,沿着路径 E2-E4-E5 到达顶点 B。因此,我们将再次发现图中存在一个循环。这里,你可以看到我们在遍历一条路径时只考虑了每条边一次。
相反,考虑下图。

Acyclic Graph
这里,我们不能在从一个顶点开始而不重复任何边之后到达同一个顶点。所以,我们会说这个图不包含任何圈。
无向图中的圈检测算法
现在我们对什么是循环有了一个大概的了解,让我们制定一个算法来检测无向图中的循环。为此,我们将从源顶点开始,并使用广度优先搜索算法遍历该图。在遍历过程中,如果我们找到一个已经遍历过的顶点,我们就说这个图中存在一个圈。
检测无向图中的循环的算法可以用公式表示如下。
- 创建一个空队列。
- 创建一个 visited_vertices 列表来跟踪已访问的顶点。
- 将源顶点插入 Q 和 visited_vertices。
- 如果 Q 为空,则转到 10。否则转到 5。
- 从 q 中取出一个顶点 v。
- 如果 v 的任何邻居已经存在于 visited_vertices 中,转到 7。否则,转到 8。
- 图表中显示了打印周期。转到 11。
- 将未访问的相邻顶点插入 Q 和已访问的顶点。
- 转到第 5 页。
- 打印图形中没有循环。
- 停下来。
Python 程序检测无向图中的循环
因为我们已经制定了检测无向图中的循环的算法,所以让我们用 python 实现它,并对前面几节中的图像中给出的图执行它。
输出:
结论
在这篇文章中,我们讨论了在无向图中检测圈的算法。这里,我们使用了广度优先图遍历算法。要了解二叉树遍历算法,可以阅读[中的顺序树遍历算法](https://www.pythonforbeginners.com/data-structures/in-order-tree-traversal-in-python)或[中的层次顺序树遍历算法](https://www.pythonforbeginners.com/data-structures/level-order-tree-traversal-in-python)。
Python 中的开发环境
原文:https://www.pythonforbeginners.com/development/development-environment-in-python
概观
Some of the steps needed to setup a development environment includes:
Operating system - e.g Linux / Mac
Project structure - project structure
Virtualenv - isolated installation of the project
Pip - a tool for installing and managing Python packages
Git - source control
Webserver - where we can manage our applications
Fabric - automated deployment
项目结构
Create an empty top-level directory for our new project.
helloflask/
-static/
-css
-font
-img
-js
-templates
-routes.py
**Then cd into the directory**
cd helloflask
Virtualenv(虚拟环境)
Many developers uses virtualenv (virtual environment) on their computer, which
is useful when you want to run several applications on the same computer.
Virtualenv will manage all dependencies and enables multiple side-by-side
installations of Python, one for each project.
It doesn't install separate copies of Python, but provides a way to keep
different project environments isolated.
If we want to run more than one (which is often the case) web application on
that host, then you should really install 'Virtualenv'.
If you don't use virtualenv , you will have it all globally installed.
安装 Virtualenv
Download and Install Virtualenv into a virtual environment
# If you are using Linux/Mac:
sudo pip install virtualenv
设置新项目
Navigate to the directory you want your project in:
$ virtualenv venv # this creates the folder venv
$ source venv/bin/activate # start working on your new project
(venv)$ pip install Flask # installs Flask
For more information on how to download install virtualenv, see [this](https://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv "virtualenv_install") article.
点
PIP is a tool for installing and managing Python packages.
PIP comes with a command-line interface, which makes installing Python software
packages as easy as issuing one command
pip install some-package-name
Users can also easily implement the package's subsequent removal
pip uninstall some-package-name
Pip has a feature to manage full lists of packages and corresponding version
numbers through a "requirements" file.
This permits the efficient re-creation of an entire group of packages in a
separate environment (e.g. another computer) or virtual environment.
This can be achieved with a properly formatted requirements.txt file
pip install -r requirements.txt
This makes dependencies easy, you can create a requirements file based on a set of
packages installed in your virtual environment.
pip freeze > requirements.txt
When deploying to a server it is important to register which requirements we need.
The requirements file can be done automatically using the freeze command for pip.
This command will generate a plain text file that contains the names of the
required Python packages and their versions, for example **Flask==0.9**
To do this we freeze the installed packages and store this setup in a
requirements.txt file
$ cat requirements.txt
Flask==0.9
Jinja2==2.6
Werkzeug==0.8.3
The requirements file can be used to rebuild a virtual environment or to deploy a
virtual environment into the machine.
开始编码
Now that we have a clean Flask environment to work in, we'll create our simple
application.
The simplest Flask App looks something like this:
Put this code into the file and name it 'hello.py'
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
github–中央存储库
Now it's time to create the repository on Github. The purpose of setting up a
Github project, is so that we can push files from our local computer to Github
and then pull the files from Github to our web server.
Create a new Github account and create a new project (helloflask)
git–本地计算机
By using a versioning system, we can store all our files in a Github repository.
The first thing you need to do on your **local computer** is to install and setup git.
Install Git
To install git, simple run:
sudo apt-get install git
进入设置
Put in your username and email into the .gitconfig file (~/.gitconfig)
git config --global user.name "pythonforbeginners"
git config --global user.email [email protected]
Git 忽略
Since our current directory contains a lof of extra files, we'll want to
configure our repository to ignore these files with a **.gitignore** file:
venv
*.pyc
Next, we’ll create a new git repository and save our changes.
# Initialize Git in our project directory
git init
This creates a git repository in the current directory.
Add all of our files to our initial commit
git add .
Check the status, this will list all files
git status
With the files added to the Git index, we can now **commit** them to our repo:
$ git commit -m 'Initial commit'
Now we have created a local Git repository for our application (local) files.
Setup Github as the origin
git remote add origin [email protected]:USERNAME/helloflask.git
git push -u origin master
Web 服务器–主机
Now its time to start up the web server and do some configuration.
If you want to use **Apache** as a web server, you can install it like this:
sudo apt-get install apache2
Configure a **virtual host** (vhost) in /etc/apache2/sites-available/siteX
Install **virtualenv** just like you did on your local computer.
Set up the environment for the website, here I use /var/www
Cd into that folder and **clone the project** that you setup on Github, by typing:
git clone [email protected]:USERNAME/helloflask.git
Initialize and activate your virtualenv
virtualenv helloflask
cd helloflask
source bin/activate
Install dependencies
pip install -r requirements.txt
构造
Fabric is used for deployment. You can of course always manually upload the code
and restart the web server to reflect the configuration changes.
Using fabric in a development environment, where you have multiple servers with
multiple people pushing the code multiple times per day, this can be incredible
very useful.
Fabric can configure the system, execute commands on local/remote server, deploy
your application, do rollbacks etc.
It does that by using its command-line utility that will run a fabfile containing
instructions on how to deploy to a server.
A common practice when developing is to use Git to deploy and Fabric to automate
it.
安装结构
pip install fabric
Fabric expects a fabfile named fabfile.py which defines all of the actions we can
take.
The fabfile.py should be in your project's root directory.
I like to use this script that asks the server to pull from the git repository
and restart apache. [[source]](https://yuji.wordpress.com/2011/04/09/django-python-fabric-deployment-script-and-example/ "fabric_script")
from fabric.api import * # import fabrics API functions
env.hosts = ['[email protected]:22'] # add the remote server information
def pushpull():
local('git push') # runs the command on the local environment
run('cd /path/to/project/; git pull') # runs the command on the remote environment
#Run it with:
$ fab pushpull
For more information on how to use fabric in a development environment, please
refer to [this](https://www.pythonforbeginners.com/systems-programming/how-to-use-fabric-in-a-development-environment "fabric_in_a_dev") article.
Python 中常见的字典操作
原文:https://www.pythonforbeginners.com/dictionary/dictionary-common-dictionary-operations
词典
A dictionary constant consists of a series of key-value pairs enclosed by curly
braces { }
With dictionaries you can store things so that you quickly can find them again
字典操作
Below is a list of common dictionary operations:
**create an empty dictionary** x = {}
**create a three items dictionary** x = {"one":1, "two":2, "three":3}
**access an element** x['two']
**get a list of all the keys** x.keys()
**get a list of all the values** x.values()
**add an entry** x["four"]=4
**change an entry** x["one"] = "uno"
**delete an entry** del x["four"]
**make a copy** y = x.copy()
**remove all items** x.clear()
**number of items** z = len(x)
**test if has key** z = x.has_key("one")
**looping over keys** for item in x.keys(): print item
**looping over values** for item in x.values(): print item
**using the if statement to get the values** if "one" in x:
print x['one']
if "two" not in x:
print "Two not found"
if "three" in x:
del x['three']
Python 中的词典理解
原文:https://www.pythonforbeginners.com/dictionary/dictionary-comprehension-in-python
在 python 中使用字典时,可能会出现这样的情况:我们需要根据某个条件通过包含字典中的某些项来从另一个字典创建一个新的字典,或者我们希望创建一个新的字典,其中包含符合特定条件的键和值。我们可以通过使用 for 循环逐个手工检查字典条目,并将它们添加到新字典中来实现。在本教程中,我们将看到如何使用 python 中一个名为 dictionary comprehension 的简洁结构来达到同样的效果。
什么是词典理解?
就像列表理解是一种从其他列表创建列表的方法,字典理解是一种从另一个字典或任何其他可迭代对象创建 python 字典的方法。我们可以根据条件语句用原始字典中的相同元素创建新字典,或者根据需要转换字典中的条目。在使用字典理解创建新字典时,我们可以修改字典中条目的键或值或者键和值。
在使用字典理解创建字典时,我们必须从任何字典或任何其他 iterable 中获取一个键值对。字典理解的语法如下。
myDict={key:value for var in iterable}
当使用 list 或 tuple 的元素作为键和从这些元素派生的值从 list 或 tuple 创建字典时,我们可以使用下面的语法。
myDict={key:value for var in list_name}
myDict={key:value for var in tuple_name}
当从另一个字典创建一个字典时,我们可以使用下面的语法。
myDict={key:value for (key,value) in dict_name.items()}
如何利用字典理解?
我们可以通过使用列表中的元素来创建字典。假设我们想要创建一个 python 字典,用列表中的元素作为键和值,那么我们可以这样做。
myList=[1,2,3,4]
myDict={x:x for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)
输出:
List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 2, 3: 3, 4: 4}
在输出中,我们可以看到创建的字典具有与给定列表中的元素相同的键和值。
我们还可以在创建新字典时,在将列表元素添加到字典之前修改它们。假设我们想创建一个字典,把列表中的元素作为键,它们的平方作为值,我们可以这样做。
myList=[1,2,3,4]
myDict={x:x**2 for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)
输出:
List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
在输出中,我们可以看到创建的字典将列表中的元素作为键,将它们的方块作为值。
在创建字典时,我们还可以根据条件有选择地使用列表中的条目。假设我们想创建一个字典,它的列表元素是偶数键,它们的平方是值,我们可以这样做。
myList=[1,2,3,4]
myDict={x:x**2 for x in myList if x%2==0}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)
输出:
List is:
[1, 2, 3, 4]
Created dictionary is:
{2: 4, 4: 16}
在输出中,我们可以看到,在创建的字典中,只有那些偶数的列表元素被用作键,它们的平方是字典的键的相应值。
我们也可以通过使用另一个字典中的条目来创建一个字典。为此,我们可以使用items()方法从原始字典中提取键值对。items() 方法给出了一个元组列表作为(key,value)对,我们可以用它来创建一个新的字典。
例如,我们可以使用字典理解创建一个与给定字典完全一样的新字典,如下所示。
myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value for (key,value) in myDict.items()}
print("New dictionary is:")
print(newDict)
输出:
Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{1: 1, 2: 2, 3: 3, 4: 4}
在输出中,我们可以看到新字典包含与原始字典相同的键值对。
我们还可以修改原始字典中的字典条目,然后将它们包含到新字典中。例如,下面的程序在将条目添加到新字典之前修改了它们的值。
myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items()}
print("New dictionary is:")
print(newDict)
输出:
Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
在输出中,我们可以看到新字典的键与原始字典的键相同,但是新字典中项的值是原始字典中项的值的平方。
我们还可以在创建新字典时使用条件从旧字典中有选择地选择条目。
例如,下面的程序过滤掉键是奇数的项,并且只考虑那些要添加到键是偶数的新字典中的项。在将这些条目添加到新字典之前,它进一步平方这些条目的值。
myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items() if key%2==0}
print("New dictionary is:")
print(newDict)
输出:
Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{2: 4, 4: 16}
在输出中,我们可以看到新字典中的键值对只有偶数作为它们的键,它们的平方作为各自的值。
结论
在本文中,我们已经了解了什么是词典理解,以及如何使用它们来创建新词典。字典理解可用于在创建字典时替换 for 循环,并在不使用复杂条件时使源代码更加简洁并增加代码的可读性。如果我们在字典理解中使用复杂的条件语句,可能会降低源代码的可读性。代码的执行也可能会变慢,程序将需要更多的内存空间。因此,在处理复杂的条件语句来创建字典时,最好使用 for 循环而不是字典理解。请继续关注更多内容丰富的文章。
Python 中的字典操作
原文:https://www.pythonforbeginners.com/dictionary/dictionary-manipulation-in-python
概观
字典是键值对的集合。
字典是一组键:值对。
字典中的所有键必须是唯一的。
在字典中,键和值由冒号分隔。
键、值对用逗号分隔。
键和值对列在大括号“{ }”之间
我们使用方括号“[ ]”查询字典
词典操作
每当你需要将你想要的条目链接在一起时,字典就很有用,例如存储结果以便快速查找。
创建一个空字典
months = {}
用一些对子创建一个字典
注意:每个键必须是唯一的
months = { 1 : "January",
2 : "February",
3 : "March",
4 : "April",
5 : "May",
6 : "June",
7 : "July",
8 : "August",
9 : "September",
10 : "October",
11 : "November",
12 : "December" }
月份[1-12]是键,“1 月-12 月”是值
打印所有密钥
print "The dictionary contains the following keys: ", months.keys()
输出:
该字典包含以下关键字:[1,2,3,4,5,6,7,8,9,10,
11,12]
访问
要从字典中获取一个值,您必须提供它的键,您不能提供值并获取键
whichMonth = months[1]
print whichMonth
产出:1 月
要从字典中删除元素,请使用 del
del(months[5])
print months.keys()
输出:
【1,2,3,4,6,7,8,9,10,11,12】
要向字典中添加新元素,请为新键赋值
months[5] = "May"
print months.keys()
输出:
【1,2,3,4,5,6,7,8,9,10,11,12】
要更新字典中的元素,请为其键分配一个新值
months[1] = "Jan"
print months
输出:
整理
sortedkeys = months.keys()
print sortedkeys
输出:
【1,2,3,4,5,6,7,8,9,10,11,12】
字典和循环
遍历键
for key in months:
print key, months[key]
输出:
1 月 1 日
2 月 2 日
3 月
4 月
5 月
6 月
7 月
8 月
9 月
10 月
11 月
12 月
迭代(键,值)对
for key, value in months.iteritems():
print key, value
print "The entries in the dictionary are:"
for item in months.keys():
print "months[ ", item, " ] = ", months[ item ]
结合列表和字典
字典列表示例
customers = [{"uid":1,"name":"John"},
{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},
]
print customers
Output:
[{'uid': 1,' name': 'John'},{'uid': 2,' name': 'Smith'},{'uid': 3,' name ':【T1]' Andersson ' }]
打印每个客户的 uid 和姓名
for x in customer:
print x["uid"], x["name"]
输出:
1 约翰
2 史密斯
3 安德森
修改条目
这将把客户 2 的名字从 Smith 改为 Charlie
customers[2]["name"]="charlie"
print customers
输出:
[{'uid': 1,' name': 'John'},{'uid': 2,' name': 'Smith'},{'uid': 3,' name ':【T1]' Charlie ' }]
向每个条目添加一个新字段
for x in customers:
x["password"]="123456" # any initial value
print customers
输出:
[{'password': '123456 ',' uid': 1,' name': 'John'},{'password': '123456 ',' uid':
2,' name': 'Smith'},{'password': '123456 ',' uid': 3,' name': 'Andersson'}]
删除字段
del customers[1]
print customers
Output:
[{'uid': 1,' name': 'John'},{'uid': 3,' name': 'Andersson'}]
删除所有字段
# This will delete id field of each entry.
for x in customers:
del x["id"]
Output:
[{'name': 'John'},{'name': 'Smith'},{'name': 'Andersson'}]
有关字典的更多信息,请参见这篇文章。
Python 中的字典是什么?
Dictionary 是 Python 中的另一种数据类型。
字典是具有“键”和“值”的条目的集合。
Python 字典也称为关联数组或哈希表。
它们就像列表一样,除了没有指定的索引号,而是由你自己编索引。
字典是无序的,所以添加键的顺序并不一定反映它们被报告回来的顺序。
使用{}花括号来构造字典。
使用[]查找与键相关联的值
提供一个键和值。
冒号放在键和值之间(键:值)
每个键必须是唯一的,并且每个键在字典中只能出现一次。
如何创建字典?
要创建字典,请提供键和值,并确保每一对用逗号分隔
# This is a list
mylist = ["first","second","third"]
# This is a dictionary
mydictionary = {0:"first",1:"second",2:"third"}
让我们创建一些随机字典:
# Empty declaration + assignment of key-value pair
emptyDict = {}
emptyDict['key4']=’value4?
# Create a three items dictionary
x = {"one":1,"two":2,"three":3}
#The name of the dictionary can be anything you like
dict1 = {'abc': 456};
dict2 = {'abc':123,98.6:37};
访问/获取值
要访问字典元素,可以使用方括号和键
来获取它的值。
data = {'Name':'Zara','Age':7,'Class':'First'};
# Get all keys
data.keys()
# Get all values
data.values()
# Print key1
print data['Name']
# Prints 7
print data['Age']
# Prints name and age
print 'Name', data['Name'];
print 'Age', data['Age'];
在字典中循环
默认情况下,字典上的 for 循环遍历它的键。
这些键将以任意顺序出现。
方法 dict.keys()和 dict.values()显式返回键或值
的列表。
还有一个 items()返回(键,值)元组的列表,这是检查字典中所有键值数据的最有效的方法。
所有这些列表都可以传递给 sorted()函数。
基本语法循环遍历字典(键和值)
输入数据:
打印数据[key]
假设你有一本名为“数据”的字典
data = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'
}
for key, value in data.items():
print key,value
Looping their values directory (not in order)
for value in data.values():
print value
更新字典
如果字典中没有该关键字,则创建一个新条目。
如果密钥已经存在,则覆盖以前的值。
您可以通过以下方式更新词典:
添加新的条目或项目(即,键值对)
修改现有条目
删除现有条目
让我们看看它是如何工作的:
data = {'Name':'Zara','Age':7,'Class':'First'};
data['Age'] = 8; # update existing entry
data['School'] = "DPS School"; # Add new entry
print "data['Age']: ", data['Age'];
print "data['School']: ", data['School'];
我们再举一个例子:
birthday = {}
birthday['Darwin'] = 1809
birthday['Newton'] = 1942 # oops
birthday['Newton'] = 1642
print birthday
删除键/值
“del”运算符执行删除操作。
在最简单的情况下,它可以删除变量的定义,就像变量
没有被定义一样。
Del 也可以用在列表元素或片上,以删除列表的这一部分,并从字典中删除条目。
data = {'a':1,'b':2,'c':3}
del dict['b'] ## Delete 'b' entry
print dict ## {'a':1, 'c':3}
来自谷歌课堂的例子
让我们看看这个来自 https://developers.google.com/edu/python/dict-files 的例子
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
print dict['a'] ## Simple lookup, returns 'alpha'
dict['a'] = 6 ## Put new key/value into dict
'a' in dict ## True
## print dict['z'] ## Throws KeyError
if 'z' in dict: print dict['z'] ## Avoid KeyError
print dict.get('z') ## None (instead of KeyError)
默认情况下,字典上的 for 循环遍历它的键。
这些键将以任意顺序出现。
方法 dict.keys()和 dict.values()显式返回键或值
的列表。
还有一个 items()返回(键,值)元组的列表,这是检查字典中所有键值数据的最有效的方法。
所有这些列表都可以传递给 sorted()函数。
## Note that the keys are in a random order.
for key in dict: print key
## prints a g o
## Exactly the same as above
for key in dict.keys(): print key
## Get the .keys() list:
print dict.keys() ## ['a', 'o', 'g']
## Likewise, there's a .values() list of values
print dict.values() ## ['alpha', 'omega', 'gamma']
## Common case -- loop over the keys in sorted order,
## accessing each key/value
for key in sorted(dict.keys()):
print key, dict[key]
## .items() is the dict expressed as (key, value) tuples
print dict.items() ## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
## This loop syntax accesses the whole dict by looping
## over the .items() tuple list, accessing one (key, value)
## pair on each iteration.
for k, v in dict.items(): print k, '>', v
## a > alpha o > omega g > gamma
字典格式
%操作符可以方便地将字典中的值按名称替换成字符串
hash = {}
hash['word'] = 'garfield'
hash['count'] = 42
s = 'I want %(count)d copies of %(word)s' % hash # %d for int, %s for string
# Will give you:
>> 'I want 42 copies of garfield'
常见字典操作
# create an empty dictionary
x = {}
# create a three items dictionary
x = {"one":1, "two":2, "three":3}
# get a list of all the keys
x.keys()
# get a list of all the values
x.values()
# add an entry
x["four"]=4
# change an entry
x["one"] = "uno"
# delete an entry
del x["four"]
# make a copy
y = x.copy()
# remove all items
x.clear()
#number of items
z = len(x)
# test if has key
z = x.has_key("one")
# looping over keys
for item in x.keys(): print item
# looping over values
for item in x.values(): print item
# using the if statement to get the values
if "one" in x:
print x['one']
if "two" not in x:
print "Two not found"
if "three" in x:
del x['three']
来源
https://developers.google.com/edu/python/dict-files http://docs.python.org/2/tutorial/datastructures.htmlhttp://software-carpentry.org/3_0/py04.html
http://yuji.wordpress.comT12)http://www.tutorialspoint.com/python/python_dictionary.htm
Python 中注释和文档字符串的区别
原文:https://www.pythonforbeginners.com/comments/difference-between-comments-and-docstrings-in-python
注释用于增加源代码的可读性和可理解性。python 注释可以是单行注释,也可以是使用单行注释或多行字符串常量编写的多行注释。文档字符串或文档字符串在 python 中也是多行字符串常量,但是它们有非常特殊的属性,不像 python 注释。在本文中,我们将看看 python 中注释和文档字符串之间的区别。
python 中的注释声明
python 中的单行注释使用#符号声明,如下所示。
#This is a single line comment.
Python 基本上没有多行注释,但是我们可以使用多个单行注释在 python 中编写多行注释,如下所示。示例中给出的函数将一个数字及其平方作为键值对添加到一个 python 字典中。
#This is a multiline comment
#written using single line comments
def add_square_to_dict(x,mydict):
a=x*x
mydict[str(x)]=a
return mydict
我们还可以使用多行字符串常量在 python 中实现多行注释,如下所示。这里声明了多行字符串,但没有将其赋给任何变量,因为没有为它分配内存,它的工作方式就像一个注释。
"""This is a multiline comment
written using multiline strings """
我们应该记住,使用#符号编写的注释不需要遵循缩进规则,但是使用多行字符串编写的注释必须遵循声明它们的块的缩进。
python 中文档字符串的声明
docstring 是与任何 python 对象或模块相关联的字符串常量。该对象可以是类、方法或函数。docstring 的编写类似于使用多行字符串的多行注释,但它必须是对象定义中的第一条语句。
python 中类的 docstring 声明如下。
class MyNumber():
"""This is the docstring of this class.
It describes what this class does and all its attributes."""
def __init__(self, value):
self.value=value
方法的 docstring 声明如下。
class MyNumber():
"""This is the docstring of this class.
It describes what this class does and all its attributes."""
def __init__(self, value):
self.value=value
def increment(self):
"""This is the docstring for this method.
It describes what the method does, what are its calling conventions and
what are its side effects"""
self.value=self.value+1
return self.value
函数的 docstring 声明如下。
def decrement(number):
"""This is the docstring of this function.
It describes what the function does, what are its calling conventions and
what are its side effects"""
number=number-1
return number
在 python 中访问注释
执行程序时不能访问注释,因为它们不与任何对象相关联。只有当某人有权访问源代码文件时,才能访问注释。
在 python 中访问文档字符串
我们可以使用任何 python 对象的__doc__属性来访问与该对象相关联的 docstring,如下所示。
一个类的 docstring 可以由className.__doc__ 访问,如下所示。
class MyNumber():
"""This is the docstring of this class.
It describes what this class does and all its attributes."""
def __init__(self, value):
self.value=value
def increment(self):
"""This is the docstring for this method.
It describes what the method does, what are its calling conventions and
what are its side effects"""
self.value=self.value+1
return self.value
print (MyNumber.__doc__)
输出:
This is the docstring of this class.
It describes what this class does and all its attributes.
方法的 docstring 可以使用className.methodName.__doc__来访问,如下所示。
class MyNumber():
"""This is the docstring of this class.
It describes what this class does and all its attributes."""
def __init__(self, value):
self.value=value
def increment(self):
"""This is the docstring for this method.
It describes what the method does, what are its calling conventions and
what are its side effects"""
self.value=self.value+1
return self.value
print (MyNumber.increment.__doc__)
输出:
This is the docstring for this method.
It describes what the method does, what are its calling conventions and
what are its side effects
可以使用functionName.__doc__访问函数的 docstring,如下所示。
def decrement(number):
"""This is the docstring of this function.
It describes what the function does, what are its calling conventions and
what are its side effects"""
number=number-1
return number
print (decrement.__doc__)
输出:
This is the docstring of this function.
It describes what the function does, what are its calling conventions and
what are its side effects
在 python 中使用注释的目的
注释用于增加代码的可理解性,它们通常解释为什么在程序中使用了一个语句。
在 python 中使用 docstring 的目的
docstring 以大写字母开始,以句点结束,它描述了与之相关联的对象的元数据,包括参数、调用约定、副作用等。文档字符串用于将文档与 python 中的类、方法和函数等对象相关联,它们描述了对象的功能。
结论
在本文中,我们通过查看注释和文档字符串在源代码中是如何声明的以及它们的用途来了解它们之间的区别。请继续关注更多内容丰富的文章。
Python 中 Pop 和 Remove 的区别
原文:https://www.pythonforbeginners.com/basics/difference-between-pop-and-remove-in-python
在各种任务中,我们需要从列表中删除或提取元素。我们通常使用pop()方法和remove()方法来实现。在本文中,我们将讨论 python 中 pop()方法和 remove()方法的主要区别。
pop()方法
方法用来从一个给定的列表中提取一个元素。当在列表上调用时,它接受元素的index作为可选的输入参数,并在从列表中删除元素后返回给定索引处的元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
element = myList.pop(2)
print("The popped element is:", element)
print("The updated list is:", myList)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The popped element is: 3
The updated list is: [1, 2, 4, 5, 6, 7]
如果我们不提供任何索引作为输入参数,它将删除最后一个索引处的元素并返回值。
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
element = myList.pop()
print("The popped element is:", element)
print("The updated list is:", myList)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The popped element is: 7
The updated list is: [1, 2, 3, 4, 5, 6]
remove()方法
方法也被用来从列表中删除一个元素。在列表上调用remove()方法时,该方法将需要删除的元素的值作为输入参数。执行后,它从列表中删除输入元素的第一个匹配项。您可以在下面的示例中观察到这一点。
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
myList.remove(3)
print("The removed element is:", 3)
print("The updated list is:", myList)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The removed element is: 3
The updated list is: [1, 2, 4, 5, 6, 7]
remove()方法不返回任何值。
Pop 和 Remove 的区别
pop()方法和remove()方法的主要区别在于,pop()方法使用元素的索引来删除它,而remove()方法将元素的值作为输入参数来删除元素,正如我们在上面已经看到的。- 可以在没有输入参数的情况下使用
pop()方法。另一方面,如果我们使用没有输入参数的remove()方法,程序将会出错。 pop()方法返回被删除元素的值。然而,remove()方法不返回任何值。- 如果我们在一个空列表上调用
pop()方法,它将引发一个IndexError异常。另一方面,如果我们在一个空列表上调用remove()方法,它将引发ValueError异常。
结论
在本文中,我们讨论了 python 中列表的 pop()方法和 remove()方法之间的区别。要了解更多关于列表的知识,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的集合理解的文章。
建议阅读:
Python 中收益和回报的区别
原文:https://www.pythonforbeginners.com/basics/difference-between-yield-and-return-in-python
在用 python 编程时,您可能使用过 yield 和 return 语句。在本文中,我们将讨论回报率和收益率关键字的理论概念。我们还将看看 python 中 yield 和 return 语句的不同之处。
Python 中的 yield 和 return 是什么?
Yield 和 return 是 python 中的关键词。它们在函数中用于在程序中将值从一个函数传递到另一个函数。
return 关键字
return 语句在函数中用于将对象返回给调用方函数。我们可以返回单个值,如数字、字符串或容器对象,如 python 字典、元组或列表。
例如,sumOfNums()函数在下面的源代码中向调用者返回一个数字。
def sumOfNums(num1, num2):
result = num2 + num1
return result
output = sumOfNums(10, 20)
print("Sum of 10 and 20 is:", output)
输出:
Sum of 10 and 20 is: 30
类似地,我们可以使用 return 语句返回容器对象,如下例所示。这里,函数“square”将一列数字作为输入,并返回输入列表中元素的平方列表。
def square(list1):
newList = list()
for i in list1:
newList.append(i * i)
return newList
input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output list is:", output)
输出:
input list is: [1, 2, 3, 4, 5, 6]
Output list is: [1, 4, 9, 16, 25, 36]
一个函数中可以有多个 return 语句。但是,一旦在程序中执行了 return 语句,return 语句之后写的语句就永远不会被执行。
yield 关键字
yield 语句也在函数中用于向调用函数返回值。但是收益声明以不同的方式工作。当 yield 语句在函数中执行时,它向调用者返回一个生成器对象。可以使用 next()函数或 for 循环访问 generator 对象中的值,如下所示。
def square(list1):
newList = list()
for i in list1:
newList.append(i * i)
yield newList
input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output from the generator is:", output)
print("Elements in the generator are:",next(output))
输出:
input list is: [1, 2, 3, 4, 5, 6]
Output from the generator is: <generator object square at 0x7fa59b674a50>
Elements in the generator are: [1, 4, 9, 16, 25, 36]
一个函数可以有多个 yield 语句。当执行第一条 yield 语句时,它会暂停函数的执行,并向调用函数返回一个生成器。当我们使用 next()函数在生成器上执行下一个操作时,该函数再次恢复并执行,直到下一个 yield 语句。这个过程可以持续到函数的最后一个语句。您可以通过下面的例子来理解这一点。
def square(list1):
yield list1[0]**2
yield list1[1] ** 2
yield list1[2] ** 2
yield list1[3] ** 2
yield list1[4] ** 2
yield list1[5] ** 2
input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output from the generator is:", output)
print("Elements in the generator are:")
for i in output:
print(i)
输出:
input list is: [1, 2, 3, 4, 5, 6]
Output from the generator is: <generator object square at 0x7fa421848a50>
Elements in the generator are:
1
4
9
16
25
36
您应该记住,当在执行完最后一个 yield 语句后将生成器传递给 next()函数时,它会导致 StopIteration 错误。可以通过在除了块之外的 python try 中使用 next()函数来避免。
收益和回报之间的差异
python 中 yield 和 return 语句的工作方式有两个主要区别。
- Return 语句停止函数的执行。而 yield 语句只暂停函数的执行。
- 程序中写在 return 语句之后的语句是不可达的,并且永远不会被执行。另一方面,在 yield 语句之后编写的语句在函数恢复执行时执行。
结论
在本文中,我们学习了 Python 中的 yield 和 return 语句。我们还研究了收益和回报语句之间的差异。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
使用 Python 进行 DNS 查找
原文:https://www.pythonforbeginners.com/code-snippets-source-code/dns-lookup-python
套接字模块提供了一种简单的方法来查找主机名的 ip 地址。
import socket
addr1 = socket.gethostbyname('google.com')
addr2 = socket.gethostbyname('yahoo.com')
print(addr1, addr2)
这将输出以下 ip 地址:
173.194.121.9 98.138.253.109
Python 中的双向链表
原文:https://www.pythonforbeginners.com/basics/doubly-linked-list-in-python
在 python 编程中,链表用于各种应用程序中。在本文中,我们将用 python 实现一个双向链表。为了理解双向链表,你需要有简单链表的知识。因此,如果你不知道单链表,你可以在这篇关于 python 中的链表的文章中读到它们。
什么是双向链表?
双向链表是一种链表,其中的节点使用两个引用相互链接。
双向链表中的每个节点由三个属性组成,即data、next和previous。您可以将双向链表中的节点可视化,如下所示。
这里,
previous属性用于引用链表中的前一个节点。data属性用于存储节点中的数据。next属性用于引用链表中的下一个节点。
在双向链表中,可以有任意数量的节点。链表中的所有节点使用 previous 和 next 属性相互连接。您可以想象一个有三个节点的双向链表,如下所示。

Doubly Linked List in Python
在上图中,我们创建了一个包含三个节点的双向链表。
- 第一个节点的
data属性中包含 5,p1 和 n1 分别作为其previous和next属性。 - 第二个节点在其
data属性中包含 10,p2 和 n2 分别作为其previous和next属性。 - 第三个节点在其
data属性中包含 15,p3 和 n3 分别作为其previous和next属性。 head节点不包含任何数据,用于引用链表中的第一个节点。- 第一个节点的
previous属性不引用任何其他节点。它指向None。类似地,最后一个节点的next属性不引用任何其他节点。也指向了None。
因为我们对双向链表有一个大致的概念,所以让我们试着用 Python 实现一个双向链表。
如何用 Python 创建双向链表?
为了在 python 中创建双向链表,我们将首先为双向链表创建一个节点,如下所示。
class Node:
def __init__(self, value):
self.previous = None
self.data = value
self.next = None
这里,Node类包含属性data来存储链表中的数据。在 python 中,previous和next属性用于连接双向链表中的节点。
创建节点后,我们将创建一个DoublyLinkedList类来实现 python 中的双向链表。该类将包含一个初始化为None的head属性。
class DoublyLinkedList:
def __init__(self):
self.head = None
创建空链表后,我们可以创建一个节点,并将其分配给head属性。要向链表添加更多的节点,可以手动分配节点的next和previous属性。
我们可以编写一个方法,在 python 中的双向链表中插入一个元素,而不是手动将节点分配给链表。我们还可以执行不同的操作,比如在 python 中更新和删除双向链表中的元素。让我们逐一讨论每个操作。
检查 Python 中的双向链表是否为空
要检查 python 中的双向链表是否为空,我们只需检查链表的head属性是否指向None。如果是,我们就说链表是空的。否则不会。
对于这个操作,我们将实现一个 isEmpty() 方法。当在双向链表上调用isEmpty()方法时,它将检查链表的head属性是否指向None。如果是,则返回True。否则返回False。
下面是检查双向链表是否为空的 isEmpty()方法的 python 实现。
def isEmpty(self):
if self.head is None:
return True
return False
在 Python 中求双向链表的长度
为了找到双向链表的长度,我们将遵循以下步骤。
- 首先,我们将创建一个临时变量
temp和一个计数器变量count。 - 我们将用双向链表的
head初始化变量temp。同样,我们将把变量count初始化为 0。 - 现在我们将使用 while 循环和
temp变量遍历链表。 - 遍历时,我们会先检查当前节点(
temp)是否为None。如果是,我们将退出循环。否则,我们将首先把count加 1。之后,我们将把temp变量赋给当前节点的next节点。
在 while 循环执行之后,我们将在变量count中获得双向链表的长度。
下面是 python 中双向链表的length() 方法的实现。当在双向链表上调用时,它计算链表的长度并返回值。
def length(self):
temp = self.head
count = 0
while temp is not None:
temp = temp.next
count += 1
return count
在 Python 中搜索双向链表中的元素
为了在 python 中搜索双向链表中的元素,我们将使用下面的算法。
- 首先,我们将定义一个变量
temp,并将其初始化为链表的head属性。 - 我们还将定义一个变量
isFound,并将其初始化为False。这个变量将用于检查给定的元素是否在双向链表中找到。 - 之后,我们将使用 while 循环和
temp变量遍历链表的节点。 - 在迭代双向链表的节点时,我们将执行以下操作。
- 我们将检查当前节点是否是
None。如果是,则意味着我们已经到达了链表的末尾。因此,我们将移出 while 循环。 - 如果当前节点不是
None,我们将检查当前节点中的数据是否等于我们正在搜索的值。 - 如果当前节点中的元素等于我们正在搜索的元素,我们将把值
True赋给isFound变量。之后,我们将使用 break 语句跳出 while 循环。否则,我们将移动到链表中的下一个节点。
- 我们将检查当前节点是否是
在 while 循环执行之后,如果isFound变量的值为True,则该元素被认为是在链表中找到的。否则不会。
下面是search()方法的实现。当在双向链表上调用时,search()方法将一个元素作为它的输入参数。执行后,如果在链表中找到该元素,则返回 True。否则,它返回 False。
def search(self, value):
temp = self.head
isFound = False
while temp is not None:
if temp.data == value:
isFound = True
break
temp = temp.next
return isFound
在 Python 中的双向链表中插入元素
在 python 中向双向链表中插入元素时,可能有四种情况。
- 我们需要在链表的开头插入一个元素。
- 我们需要在链表的给定位置插入一个元素。
- 我们需要在链表的柠檬后面插入一个元素。
- 我们需要在链表的末尾插入一个元素。
让我们逐一讨论每一种情况。
在双向链表的开头插入
为了在 python 中的双向链表的开头插入一个元素,我们将首先检查链表是否为空。您可以使用上一节讨论的isEmpty()方法检查链表是否为空。
如果双向链表是空的,我们将简单地用给定的数据创建一个新的节点,并将它赋给链表的head属性。
如果链表不为空,我们将遵循以下步骤。
- 首先,我们将创建一个具有给定数据的新节点,这些数据必须插入到链表中。
- 之后,我们会将链表的
head属性所引用的节点赋给新节点的next属性。 - 然后,我们将新节点赋给链表的
head属性所引用的节点的previous属性。 - 最后,我们将新节点分配给链表的
head属性。
执行上述步骤后,新元素将被添加到双向链表的开头。
下面是 python 中insertAtBeginning()方法的实现。在双向链表上调用insertAtBeginning()方法时,该方法将一个元素作为其输入参数,并将其插入到链表的开头。
def insertAtBeginning(self, value):
new_node = Node(value)
if self.isEmpty():
self.head = new_node
else:
new_node.next = self.head
self.head.previous = new_node
self.head = new_node
在双向链表的末尾插入
为了在 python 中的双向链表的末尾插入一个元素,我们将使用下面的算法。
- 首先,我们将使用给定的元素创建一个新节点。
- 之后,我们将检查双向链表是否为空。如果是,我们将使用
insertAtBeginning()方法将新元素添加到列表中。 - 否则,我们将定义一个变量
temp并将head属性赋给它。之后,我们将使用 while 循环移动到双向链表的最后一个节点。 - 在 while 循环中,我们将检查当前节点的
next属性是否指向None。如果是,我们已经到达列表的最后一个节点。因此,我们将移出循环。否则,我们将转移到下一个节点。 - 到达最后一个节点(
temp)后,我们会将新节点赋给最后一个节点的next属性。然后,我们将把temp分配给新节点的previous属性。
执行上述步骤后,新元素将被添加到双向链表的末尾。
下面是insertAtEnd()方法的实现。在链表上调用insertAtEnd()方法时,该方法将一个元素作为其输入参数,并将其添加到链表的末尾。
def insertAtEnd(self, value):
new_node = Node(value)
if self.isEmpty():
self.insertAtBeginning(value)
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.previous = temp
在双向链表的元素后插入
要在 python 中的双向链表中的另一个元素之后插入一个新元素,我们将使用以下步骤。
首先,我们将定义一个变量temp,并将其初始化为链表的head属性。之后,我们将使用 while 循环和temp变量遍历链表的节点。在迭代双向链表的节点时,我们将执行以下操作。
- 我们将检查当前节点是否是
None。如果是,则意味着我们已经到达了链表的末尾。因此,我们将移出 while 循环。 - 如果当前节点不是
None,我们将检查当前节点中的data是否等于我们必须在其后插入新元素的元素。 - 如果当前节点中的元素等于我们必须在其后插入新元素的元素,我们将使用 break 语句退出 while 循环。否则,我们将移动到链表中的下一个节点。
执行 while 循环后,可能会出现两种情况。
-
如果
temp变量包含值None,这意味着链表中不存在我们必须在其后插入新值的元素。在这种情况下,我们将打印该元素不能插入双向链表。 -
如果
temp变量不是None,我们将在链表中插入元素。为此,我们将遵循以下步骤。- 首先,我们将用需要插入的元素创建一个新节点。
- 我们将把当前节点的下一个节点赋给新节点的
next属性。之后,我们将当前节点赋给新节点的previous属性。 - 然后,我们将新节点赋给当前节点的下一个节点的
previous属性。 - 最后,我们将新节点分配给当前节点的
next属性。
执行上述步骤后,新元素将被插入到双向链表中给定值之后。
下面是insertAfterElement()方法的实现。insertAfterElement()方法将两个值作为它的输入参数。第一个参数是要插入到链表中的新值。第二个参数是必须在其后插入新值的元素。
在执行之后,如果必须在其后插入新值的元素出现在双向链表中,则insertAfterElement()方法将新元素插入双向链表。否则,它会显示新元素不能插入到链表中。
def insertAfterElement(self, value, element):
temp = self.head
while temp is not None:
if temp.data == element:
break
temp = temp.next
if temp is None:
print("{} is not present in the linked list. {} cannot be inserted into the list.".format(element, value))
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
在双向链表中的给定位置插入
要在 python 中的双向链表中的给定位置 N 插入一个元素,我们将遵循以下步骤。
如果 N==1,则意味着必须在第一个位置插入元素。我们将使用 insertAtBeginning() 方法在双向链表中插入元素。否则,我们将遵循以下步骤。
- 首先,我们将定义一个变量
temp,并将其初始化为链表的head属性。然后,我们将初始化一个变量count为 1。 - 之后,我们将使用 while 循环和
temp变量遍历链表的节点。 - 在迭代双向链表的节点时,我们将执行以下操作。
- 我们将检查当前节点是否是
None。如果是,则意味着我们已经到达了链表的末尾。因此,我们将移出 while 循环。 - 如果当前节点不是
None,我们将检查变量 count 的值是否等于 N-1。如果是,我们将使用 break 语句跳出 while 循环。否则,我们将移动到链表中的下一个节点。
- 我们将检查当前节点是否是
执行 while 循环后,可能会出现两种情况。
- 如果
temp变量包含值None,则意味着链表中的元素少于 N-1 个。在这种情况下,我们不能在第 N 个位置插入新节点。因此,我们将打印出该元素不能插入到双向链表中。 - 如果
temp变量不是None,我们将在链表中插入元素。为此,我们将有两种选择。 - 首先我们会检查当前节点(
temp)的下一个节点是否是None,如果是,我们需要在链表的末尾插入新元素。因此,我们将使用insertAtEnd()方法进行同样的操作。 - 如果当前节点的下一个节点不是
None,我们将使用以下步骤在给定位置插入新元素。- 首先,我们将用需要插入的元素创建一个新节点。
- 我们将把当前节点的下一个节点赋给新节点的
next属性。 - 之后,我们将当前节点赋给新节点的
previous属性。 - 然后,我们将新节点赋给当前节点的下一个节点的
previous属性。 - 最后,我们将新节点分配给当前节点的
next属性。
执行上述步骤后,新元素将被插入到双向链表的给定位置。
下面是insertAtPosition()方法的实现。insertAtPosition()方法将两个值作为它的输入参数。第一个参数是要插入到链表中的新值。第二个参数是新值必须插入的位置。
执行后,insertAtPosition()方法在双向链表中的期望位置插入新元素。否则,它会显示新元素不能插入到链表中。
def insertAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position - 1:
break
count += 1
temp = temp.next
if position == 1:
self.insertAtBeginning(value)
elif temp is None:
print("There are less than {}-1 elements in the linked list. Cannot insert at {} position.".format(position,
position))
elif temp.next is None:
self.insertAtEnd(value)
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
用 Python 打印双向链表的元素
为了在 python 中打印双向链表的元素,我们将首先定义一个变量temp并将链表的head赋给它。之后,我们将使用 while 循环来遍历链表的节点。
在迭代时,我们将首先检查双向链表中的当前节点是否为None。如果是,我们将移出 while 循环。否则,我们将打印当前节点的data属性。最后,我们将使用节点的 next 属性移动到链表中的下一个节点。
下面是printLinkedList()方法的实现。在双向链表上调用printLinkedList()方法时,会打印链表的所有元素。
def printLinkedList(self):
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
在 Python 中更新双向链表中的元素
为了在 python 中更新双向链表中的元素,我们将首先定义一个变量temp并将链表的head赋给它。我们还将定义一个变量isUpdated,并将其初始化为False。之后,我们将使用 while 循环来遍历链表的节点。
在迭代时,我们将首先检查双向链表中的当前节点是否为None。如果是,我们将移出 while 循环。否则,我们将检查当前节点中的data属性是否等于需要用新值替换的值。如果是,我们将更新当前节点中的data属性,并将isUpdated中的值更新为True。最后,我们将使用 break 语句跳出 while 循环。
在执行 while 循环之后,我们将检查isUpdated是否为假。如果是,我们将打印该值没有更新。否则,我们将打印该值已更新。
下面是updateElement() 方法的实现。updateElement()方法将两个值作为它的输入参数。第一个参数是要更新的旧值。第二个参数是新值。
执行后,updateElement() 方法将给定元素更新为新值。
def updateElement(self, old_value, new_value):
temp = self.head
isUpdated = False
while temp is not None:
if temp.data == old_value:
temp.data = new_value
isUpdated = True
temp = temp.next
if isUpdated:
print("Value Updated in the linked list")
else:
print("Value not Updated in the linked list")
更新给定位置的元素
为了在 python 中更新双向链表中给定位置 N 处的元素,我们将使用下面的算法。
首先,我们将定义一个变量temp,并将其初始化为链表的head属性。然后,我们将变量 count 初始化为 1。之后,我们将使用 while 循环和temp变量遍历链表的节点。
在迭代双向链表的节点时,我们将执行以下操作。
- 我们将检查当前节点是否是
None。如果是,则意味着我们已经到达了链表的末尾。因此,我们将移出 while 循环。 - 如果当前节点不是
None,我们将检查变量 count 的值是否等于 n,如果是,我们将使用 break 语句退出 while 循环。否则,我们将移动到链表中的下一个节点。
执行 while 循环后,可能会出现两种情况。
- 如果
temp变量包含值None,则意味着链表中的元素少于 N 个。在这种情况下,我们不能更新链表中第 n 个位置的元素。因此,我们将打印该元素无法更新。 - 如果
temp变量不是None,我们将通过更新当前节点的data属性来更新链表中的第 n 个元素。
下面是updateAtPosition()方法的实现。updateAtPosition()方法将两个值作为它的输入参数。第一个参数是链表中要更新的新值。第二个参数是新值必须被赋值的位置。
执行后,updateAtPosition()方法更新双向链表中所需位置的元素。
def updateAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position:
break
count += 1
temp = temp.next
if temp is None:
print("Less than {} elements in the linked list. Cannot update.".format(position))
else:
temp.data = value
print("Value updated at position {}".format(position))
在 Python 中从双向链表中删除元素
在 python 中从双向链表中删除元素时,可能有四种情况。
- 我们需要从链表的开头删除一个元素。
- 我们需要从链表的末尾删除一个元素。
- 我们需要删除一个特定的元素。
- 我们需要从链表的给定位置删除一个元素。
让我们逐一讨论每一种情况。
从双向链表的开头删除
要从双向链表的开头删除一个元素,我们将首先检查双向链表是否为空。如果是,我们会说我们不能从链表中删除任何元素。
否则,我们将检查链表中是否只有一个元素,即头节点的next属性是否指向None。如果head节点的下一个属性是 None,我们将把None分配给head。
如果链表中有多个元素,我们将把链表的head移动到当前head的next节点。之后,我们将把None赋给新头节点的previous属性。
执行上述步骤后,链表的第一个节点将被删除。
下面是deleteFromBeginning()方法的实现。在双向链表上调用deleteFromBeginning()方法时,会删除链表的第一个节点。
def deleteFromBeginning(self):
if self.head is None:
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
self.head = self.head.next
self.head.previous = None
删除双向链表的最后一个元素
要删除 python 中双向链表的最后一个元素,我们将使用以下步骤。
- 首先,我们将检查双向链表是否为空。如果是,我们会说我们不能从链表中删除任何元素。
- 否则,我们将检查链表是否只有一个元素,即
head节点的next属性是否指向None。如果头节点的next属性是None,我们将None赋给head。 - 如果链表中有多个元素,我们将创建一个变量
temp并将head赋给该变量。之后,我们将遍历双向链表,直到到达链表的最后一个节点,即当前节点的next属性变为None。 - 到达最后一个节点后,我们会将
None赋给当前节点的上一个节点的next属性。随后,我们将把None赋给当前节点的previous属性。
通过执行上述步骤,双向链表的最后一个元素将从链表中删除。
下面是deleteFromLast()方法的实现。在双向链表上调用deleteFromLast() 方法时,会删除链表的最后一个节点。
def deleteFromLast(self):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.previous.next = None
temp.previous = None
删除双向链表中的给定元素
为了从 python 中的双向链表中删除给定的元素,我们将使用以下步骤。
- 首先,我们将检查双向链表是否为空。如果是,我们会说我们不能从链表中删除任何元素。
- 否则,我们将检查链表是否只有一个元素,即头节点的
next属性是否指向None。 - 如果
head节点的next属性为 None,我们将检查第一个节点中的元素是否是要删除的元素。如果是,我们将把None分配给head。 - 如果链表中有多个元素,我们将创建一个变量
temp并将head赋给该变量。 - 之后,我们将使用
temp变量和 while 循环遍历双向链表直到最后。 - 在遍历链表时,我们将首先检查当前节点是否是
None,即我们已经到达了链表的末尾。如果是,我们将移出 while 循环。 - 如果当前节点不是
None,我们将检查当前节点是否包含需要删除的元素。如果是,我们将使用 break 语句跳出 while 循环。
执行 while 循环后,可能会出现两种情况。
- 如果
temp变量包含值None,则意味着我们已经到达了双向链表的末尾。在这种情况下,我们不能从链表中删除元素。因此,我们将打印出该元素不能从双向链表中删除。 - 如果
temp变量不是 none,我们将从链表中删除该元素。为此,我们将有两种选择。- 首先,我们将检查当前节点是否是链表的最后一个节点,即当前节点(
temp)的下一个节点是None,如果是,我们基本上需要删除链表的最后一个节点。因此,我们将使用deleteFromLast()方法进行同样的操作。 - 如果当前节点的下一个节点不是
None,我们将使用以下步骤删除给定的元素。 - 我们将把
temp节点的下一个节点赋给temp的前一个节点的next属性。 - 然后,我们将把
temp节点的前一个节点赋给 temp 的下一个节点的previous属性。 - 最后,我们将把
None分配给temp节点的previous和next属性。
- 首先,我们将检查当前节点是否是链表的最后一个节点,即当前节点(
通过执行上述步骤,任何给定的元素,如果存在于链表中,将从链表中删除。
下面是delete()方法的实现。在双向链表上调用delete() 方法时,该方法将一个元素作为输入参数,并从链表中删除它的第一个匹配项。
def delete(self, value):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
if self.head.data == value:
self.head = None
else:
temp = self.head
while temp is not None:
if temp.data == value:
break
temp = temp.next
if temp is None:
print("Element not present in linked list. Cannot delete element.")
elif temp.next is None:
self.deleteFromLast()
else:
temp.next = temp.previous.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
从双向链表中的给定位置删除
为了在 python 中从双向链表的给定位置 N 删除一个元素,我们将使用下面的算法。
首先,我们将检查链表是否为空。如果是,我们会说我们不能删除任何元素。
之后,我们将检查 N==1,这意味着我们需要从第一个位置删除该元素。如果是,我们将使用deleteFromBeginning()方法删除第一个元素。
否则,我们将遵循以下步骤。
- 首先,我们将定义一个变量
temp,并将其初始化为链表的head属性。然后,我们将初始化一个变量count为 1。 - 之后,我们将使用 while 循环和
temp变量遍历链表的节点。 - 在迭代双向链表的节点时,我们将执行以下操作。
- 我们将检查当前节点是否是
None。如果是,则意味着我们已经到达了链表的末尾。因此,我们将移出 while 循环。 - 如果当前节点不是
None,我们将检查变量count的值是否等于 n,如果是,我们将使用 break 语句退出 while 循环。否则,我们将移动到链表中的下一个节点。
- 我们将检查当前节点是否是
执行 while 循环后,可能会出现两种情况。
- 如果
temp变量包含值None,则意味着链表中的元素少于 N 个。在这种情况下,我们不能删除链表中第 n 个位置的元素。因此,我们将打印出该元素不能从双向链表中删除。 - 如果
temp变量不为 none,我们将从链表中删除第 n 个元素。为此,我们将有两种选择。- 首先,我们将检查当前节点(
temp)的下一个节点是否为 None。如果是,则第 n 个元素是链表的最后一个元素。因此,我们将使用deleteFromEnd()方法来删除元素。 - 如果第 n 个元素不是双向链表的最后一个元素,我们将执行以下操作来删除第 n 个元素。
- 我们将把
temp(当前节点)的下一个节点赋给 temp 的前一个节点的next属性。 - 然后,我们将把
temp节点的前一个节点赋给temp的下一个节点的previous属性。 - 最后,我们将把
None分配给temp节点的previous和next属性。
- 首先,我们将检查当前节点(
通过执行上述步骤,任何给定的元素,如果存在于链表中,将从链表中删除。
下面是deleteFromPosition()方法的实现。在双向链表上调用deleteFromPosition()方法时,该方法将需要删除元素的位置作为其输入参数。执行后,它从双向链表中的指定位置删除元素。
def deleteFromPosition(self, position):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif position == 1:
self.deleteFromBeginning()
else:
temp = self.head
count = 1
while temp is not None:
if count == position:
break
temp = temp.next
if temp is None:
print("There are less than {} elements in linked list. Cannot delete element.".format(position))
elif temp.next is None:
self.deleteFromLast()
temp.previous.next = temp.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
双向链表在 Python 中的完整实现
现在我们已经讨论了用 python 实现双向链表的所有方法,让我们执行程序来观察实现。
class Node:
def __init__(self, value):
self.previous = None
self.data = value
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
if self.head is None:
return True
return False
def length(self):
temp = self.head
count = 0
while temp is not None:
temp = temp.next
count += 1
return count
def search(self, value):
temp = self.head
isFound = False
while temp is not None:
if temp.data == value:
isFound = True
break
temp = temp.next
return isFound
def insertAtBeginning(self, value):
new_node = Node(value)
if self.isEmpty():
self.head = new_node
else:
new_node.next = self.head
self.head.previous = new_node
self.head = new_node
def insertAtEnd(self, value):
new_node = Node(value)
if self.isEmpty():
self.insertAtBeginning(value)
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.previous = temp
def insertAfterElement(self, value, element):
temp = self.head
while temp is not None:
if temp.data == element:
break
temp = temp.next
if temp is None:
print("{} is not present in the linked list. {} cannot be inserted into the list.".format(element, value))
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
def insertAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position - 1:
break
count += 1
temp = temp.next
if position == 1:
self.insertAtBeginning(value)
elif temp is None:
print("There are less than {}-1 elements in the linked list. Cannot insert at {} position.".format(position,
position))
elif temp.next is None:
self.insertAtEnd(value)
else:
new_node = Node(value)
new_node.next = temp.next
new_node.previous = temp
temp.next.previous = new_node
temp.next = new_node
def printLinkedList(self):
temp = self.head
while temp is not None:
print(temp.data, sep=",")
temp = temp.next
def updateElement(self, old_value, new_value):
temp = self.head
isUpdated = False
while temp is not None:
if temp.data == old_value:
temp.data = new_value
isUpdated = True
temp = temp.next
if isUpdated:
print("Value Updated in the linked list")
else:
print("Value not Updated in the linked list")
def updateAtPosition(self, value, position):
temp = self.head
count = 0
while temp is not None:
if count == position:
break
count += 1
temp = temp.next
if temp is None:
print("Less than {} elements in the linked list. Cannot update.".format(position))
else:
temp.data = value
print("Value updated at position {}".format(position))
def deleteFromBeginning(self):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
self.head = self.head.next
self.head.previous = None
def deleteFromLast(self):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
self.head = None
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.previous.next = None
temp.previous = None
def delete(self, value):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif self.head.next is None:
if self.head.data == value:
self.head = None
else:
temp = self.head
while temp is not None:
if temp.data == value:
break
temp = temp.next
if temp is None:
print("Element not present in linked list. Cannot delete element.")
elif temp.next is None:
self.deleteFromLast()
else:
temp.next = temp.previous.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
def deleteFromPosition(self, position):
if self.isEmpty():
print("Linked List is empty. Cannot delete elements.")
elif position == 1:
self.deleteFromBeginning()
else:
temp = self.head
count = 1
while temp is not None:
if count == position:
break
temp = temp.next
if temp is None:
print("There are less than {} elements in linked list. Cannot delete element.".format(position))
elif temp.next is None:
self.deleteFromLast()
temp.previous.next = temp.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
x = DoublyLinkedList()
print(x.isEmpty())
x.insertAtBeginning(5)
x.printLinkedList()
x.insertAtEnd(10)
x.printLinkedList()
x.deleteFromLast()
x.printLinkedList()
x.insertAtEnd(25)
x.printLinkedList()
x.deleteFromLast()
x.deleteFromBeginning()
x.insertAtEnd(100)
x.printLinkedList()
输出:
True
5
5
10
5
5
25
100
结论
在本文中,我们讨论了双向链表在 python 中的实现。我希望这篇文章能帮助你学习 python 中双向链表的所有概念。如果您在实现中发现任何错误或改进,请在评论中告诉我们。
要了解更多关于 python 编程的知识,可以阅读这篇关于如何在 python 中找到列表中最大值的索引的文章。您可能还会喜欢这篇关于如何用 python 对对象列表进行排序的文章。
请继续关注更多内容丰富的文章。
快乐学习!
下载并安装 Python
原文:https://www.pythonforbeginners.com/basics/download-and-install-python
概观
Python 是一种解释型语言,这意味着在程序运行时,代码被翻译成二进制代码。
这与编译语言(C++等)不同。)其中代码首先被
编译成二进制代码。
要运行 Python 代码,你需要一个 Python 解释器。Python 有不同的
版本,不是 Python 2 就是 Python 3。要了解差异并决定使用哪一个,请查看 python.org 的这个维基页面。
安装 Python
Python 可以在大多数操作系统上使用(Linux、Unix、Mac OS X 和 Windows)
在你的电脑上安装它非常容易,在一些系统上已经有了。要查看它是否已经安装,打开一个终端并运行下面的命令
。
如果您看到来自 Python 解释器的响应,它会在初始显示中包含一个版本号
。
>> python
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
如果你没有安装 Python,你可以看看这个链接,看看如何在你使用的平台上安装它。http://www.diveintopython.net/installing_python/index.html
我如何运行我的代码?
在 Python 中有两种运行程序的方法。
要么直接在 Python shell 中键入代码。这样做的时候
你会看到你输入的每个命令的结果。
这最适合非常短的程序或测试目的。
另一种运行代码的方式是在脚本中。
Python Shell
当你在 Python Shell 中时,Python 解释器会为你翻译所有代码。
要离开帮助模式并返回到解释器,我们使用 quit 命令。
help 命令提供了一些关于 Python 的帮助
>>> help
Type help() for interactive help, or help(object) for help about object.
>>>
你也可以使用 Python Shell 来做数学(请参见我之前的关于在 Python 中使用数学的文章)
>>> 2 + 4
6
>>> 5 * 56
280
>>> 5 - 45
-40
>>>
要退出 Python Shell,请按 Ctrl+d。
Python 脚本
要将程序作为脚本运行,请打开文本编辑器(vi、pico、nano 等)。)
并放入下面的代码:
#!/usr/bin/python
print "hello world"
将文件另存为 hello.py 并退出编辑器。
# To execute the program, type python and the file name in the shell.
$python hello.py
输出应该是:
hello world
Python 脚本可以像 shell 脚本一样直接执行,方法是在脚本的开头加上
shebang,并给文件一个可执行模式。
shebang 意味着当您想从 shell 中执行脚本时,脚本可以识别解释器类型。
# The script can be given an executable mode, or permission, using the chmod command:
$ chmod +x hello.py
现在,您可以直接通过脚本的名称来执行脚本。
从 Pandas 数据框架中删除列
原文:https://www.pythonforbeginners.com/basics/drop-columns-from-pandas-dataframe
在 python 中处理数据帧时,我们经常需要在数据预处理时从数据帧中删除一个或多个列。在本文中,我们将讨论用 python 从 pandas 数据帧中删除列的不同方法。
drop()方法
drop()方法可用于从 pandas 数据帧中删除列或行。它具有以下语法。
DataFrame.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
这里,
- 当我们必须从数据帧中删除一行时,使用
index参数。index参数将必须删除的一个索引或索引列表作为其输入参数。 - 当我们需要从数据帧中删除一列时,使用
columns参数。columns 参数将需要删除的列名或列名列表作为其输入参数。 labels参数表示我们需要从数据帧中移除的索引或列标签。为了从数据帧中删除行,我们使用了index标签。为了从数据帧中删除一列,我们使用了columns标签。要删除两个或更多的列或行,我们还可以将索引的列名列表分别传递给列和索引标签。- 当我们不使用 index 和 columns 参数时,我们将需要删除的行的列名或索引传递给
labels参数作为它的输入参数。在这种情况下,我们使用axis参数来决定是删除一行还是一列。如果我们想从数据帧中删除一列,我们将axis参数设置为 1。当我们想要从数据帧中删除一行时,我们将axis参数设置为 0,这是它的默认值。 - 当我们有多级索引时,
level参数用于从数据帧中删除行或列。level参数接受我们希望从数据帧中删除的列或行的索引级别或索引名称。要删除两个或更多级别,可以将索引级别或索引名称的列表传递给level参数。 inplace参数用于决定我们是在删除操作后获得一个新的数据帧,还是想要修改原始数据帧。当inplace被设置为False时,这是它的默认值,原始数据帧不变,drop()方法在执行后返回修改后的数据帧。要修改原始数据帧,可以将inplace设置为True。errors参数用于决定我们是否希望在执行drop()方法时引发异常和错误。默认情况下,误差参数设置为“raise”。因此,如果在执行过程中出现任何问题,drop()方法会引发一个异常。如果不希望出现错误,可以将错误参数设置为“ignore”。在这之后,drop()方法将抑制所有的异常。
执行后,如果inplace参数设置为False,则drop() 方法返回修改后的数据帧。否则返回None。
在 Python 中,熊猫按名称删除列
要按名称从 pandas dataframe 中删除一列,可以将列名传递给参数labels,并在drop()方法中将参数axis设置为 1。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
output_df=grades.drop(labels="Marks",axis=1)
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
在上面的例子中,我们首先使用 read_csv()方法从 CSV 文件中读取熊猫数据帧。然后,我们调用输入数据帧上的drop()方法,将Marks" as an 输入参数设置为labels参数,并设置axis=1。您可以观察到由drop()方法返回的 dataframe 没有"Marks"列。
不使用labels和axis参数,您可以将列名传递给drop()方法中的columns参数,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
output_df=grades.drop(columns="Marks")
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
在上面的例子中,我们没有使用两个参数,即labels和axis,而是使用了columns参数来从输入数据帧中删除 "Marks" 列。
从 Pandas 数据框架中按索引删除列
除了使用列名,还可以通过索引从数据帧中删除列。
要通过索引从 pandas 数据帧中删除列,我们首先需要使用数据帧的 columns 属性获得 columns 对象。然后,我们可以对列的索引使用索引操作符,按索引删除列,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
output_df=grades.drop(labels=grades.columns[3],axis=1)
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
在上面的例子中,我们首先使用grades.columns属性获得了grades数据帧的列名。然后,我们可以获得grades.columns属性中索引 3 处的元素。最后,我们已经将值传递给了labels参数。您可以在输出中观察到由drop()方法返回的数据帧没有输入数据帧的第 4 列。因此,我们使用索引成功地删除了数据帧中的一列。
我们也可以使用columns参数代替labels参数,如下例所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
output_df=grades.drop(columns=grades.columns[3])
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
在 Python 中从数据帧中删除第一列
要删除 dataframe 的第一列,可以将索引 0 处的列名传递给参数labels,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
output_df=grades.drop(labels=grades.columns[0],axis=1)
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Roll Name Marks Grade
0 11 Aditya 85.0 A
1 12 Chris NaN A
2 14 Sam 75.0 B
3 15 Harry NaN NaN
4 22 Tom 73.0 B
5 15 Golu 79.0 B
6 27 Harsh 55.0 C
7 23 Clara NaN B
8 34 Amy 88.0 A
9 15 Prashant NaN B
10 27 Aditya 55.0 C
11 23 Radheshyam NaN NaN
在本例中,我们必须在第一个位置删除该列。因此,我们将输入数据帧的grades.columns属性的索引 0 处的元素传递给了labels参数。由于我们必须删除数据帧中的一列,我们还需要设置axis=1。
不使用labels和axis参数,您可以使用如下所示的columns参数。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
output_df=grades.drop(columns=grades.columns[0])
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Roll Name Marks Grade
0 11 Aditya 85.0 A
1 12 Chris NaN A
2 14 Sam 75.0 B
3 15 Harry NaN NaN
4 22 Tom 73.0 B
5 15 Golu 79.0 B
6 27 Harsh 55.0 C
7 23 Clara NaN B
8 34 Amy 88.0 A
9 15 Prashant NaN B
10 27 Aditya 55.0 C
11 23 Radheshyam NaN NaN
在这个例子中,我们已经将位于grades.columns 属性索引 0 的元素传递给了drop()方法中的columns参数。grades.columns属性本质上包含一个列名列表。因此,使用列的索引删除列的过程类似于使用列的名称。它只是有一些额外的计算。因此,如果我们知道数据帧中列的名称,那么直接按列名删除列总是更好。
从熊猫数据框架中删除最后一列
为了删除数据帧的最后一列,我们将首先找到最后一列的索引。为此,我们将找到数据帧的列属性的长度。在此之后,我们将通过从长度中减去 1 来找到最后一列的索引。然后,我们将使用最后一列的索引和columns属性获得最后一列的名称。最后,我们将把获得的列名传递给labels参数。执行后,drop()方法将删除数据帧的最后一列。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
lenDf=len(grades.columns)
output_df=grades.drop(labels=grades.columns[lenDf-1],axis=1)
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Marks
0 1 11 Aditya 85.0
1 1 12 Chris NaN
2 1 14 Sam 75.0
3 1 15 Harry NaN
4 2 22 Tom 73.0
5 2 15 Golu 79.0
6 2 27 Harsh 55.0
7 2 23 Clara NaN
8 3 34 Amy 88.0
9 3 15 Prashant NaN
10 3 27 Aditya 55.0
11 3 23 Radheshyam NaN
不使用labels参数,您可以使用 columns 参数从 pandas 数据帧中删除列,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
lenDf=len(grades.columns)
output_df=grades.drop(columns=grades.columns[lenDf-1])
print("The output dataframe is:")
print(output_df)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Marks
0 1 11 Aditya 85.0
1 1 12 Chris NaN
2 1 14 Sam 75.0
3 1 15 Harry NaN
4 2 22 Tom 73.0
5 2 15 Golu 79.0
6 2 27 Harsh 55.0
7 2 23 Clara NaN
8 3 34 Amy 88.0
9 3 15 Prashant NaN
10 3 27 Aditya 55.0
11 3 23 Radheshyam NaN
熊猫在 Python 中将列放到适当的位置
默认情况下,drop()方法不会修改原始数据帧。删除指定的列后,它返回修改后的数据帧。
为了从原始数据帧中删除列,我们将把参数inplace设置为True。此后,drop() 方法修改原始数据帧,而不是返回一个新的数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.drop(columns="Marks",inplace=True)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
在本例中,我们已经将inplace参数设置为True。结果,drop()方法修改了原始数据帧。
如果在 Python 中存在,熊猫会删除列
如果数据帧中不存在列名,drop() 方法会引发一个 KeyError 异常。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.drop(columns="Height",inplace=True)
print("The output dataframe is:")
print(grades)
输出
KeyError: "['Height'] not found in axis"
在这个例子中,drop()方法的 "Height" parameter that is given as an 输入参数没有作为 dataframe 中的列出现。因此,drop()方法会引发 KeyError 异常。
为了删除存在的列而不遇到异常,我们将在drop()方法中使用errors参数。您可以将误差参数设置为“ignore”。在这之后,drop()方法将抑制所有的异常。如果输入数据帧包含指定的列,它将正常执行。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.drop(columns="Marks",inplace=True,errors="ignore")
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
在上面的例子中,"Marks" 列出现在 dataframe 中。因此,它在执行drop()方法时被删除。
如果 columns 参数中指定的列在 dataframe 中不存在,drop()方法什么也不做。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.drop(columns="Height",inplace=True,errors="ignore")
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
在上面的例子中,作为drop() 方法的输入参数给出的"Height"参数没有作为 dataframe 中的列出现。因此,drop()方法对原始数据帧没有影响。
从熊猫数据框架中删除多列
要从 pandas 数据帧中删除多个列,可以将列名列表传递给 labels 参数,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.drop(labels=["Marks", "Grade"],axis=1,inplace=True)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 14 Sam
3 1 15 Harry
4 2 22 Tom
5 2 15 Golu
6 2 27 Harsh
7 2 23 Clara
8 3 34 Amy
9 3 15 Prashant
10 3 27 Aditya
11 3 23 Radheshyam
在上面的例子中,我们已经将列表 ["Marks", "Grade"] 传递给了参数labels。因此,drop()方法从输入数据帧中删除了Marks和Grade列。
代替labels参数,您可以使用columns参数从 pandas 数据帧中删除多个列,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.drop(columns=["Marks", "Grade"],inplace=True)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 14 Sam
3 1 15 Harry
4 2 22 Tom
5 2 15 Golu
6 2 27 Harsh
7 2 23 Clara
8 3 34 Amy
9 3 15 Prashant
10 3 27 Aditya
11 3 23 Radheshyam
您还可以使用列的索引从 pandas 数据帧中删除多个列,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.drop(columns=grades.columns[3:5],inplace=True)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 14 Sam
3 1 15 Harry
4 2 22 Tom
5 2 15 Golu
6 2 27 Harsh
7 2 23 Clara
8 3 34 Amy
9 3 15 Prashant
10 3 27 Aditya
11 3 23 Radheshyam
在这个例子中,我们使用了列表切片来获得数据帧的第三和第四个位置的列名。与使用列名相比,使用列索引来删除数据帧的成本更高。但是,当我们想要删除前 n 列或后 n 列,或者在没有列名的情况下从特定索引中删除列时,这是很有用的。
从熊猫数据框架中删除前 N 列
为了删除数据帧的前 n 列,我们将使用数据帧的columns属性获得 columns 对象。然后,我们可以使用带有列索引的索引操作符从数据帧中删除前 n 列,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
n=2
grades.drop(columns=grades.columns[:n],inplace=True)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Name Marks Grade
0 Aditya 85.0 A
1 Chris NaN A
2 Sam 75.0 B
3 Harry NaN NaN
4 Tom 73.0 B
5 Golu 79.0 B
6 Harsh 55.0 C
7 Clara NaN B
8 Amy 88.0 A
9 Prashant NaN B
10 Aditya 55.0 C
11 Radheshyam NaN NaN
在上面的例子中,我们获取了columns属性的一部分,以获得索引为 0 和 1 的列的列名。然后,我们将切片传递给drop()方法中的 columns 参数来删除列。
从熊猫数据框架中删除最后 N 列
为了删除数据帧的最后 n 列,我们将使用数据帧的columns属性获得 columns 对象。然后,我们可以使用带有列索引的索引操作符从数据帧中删除最后 n 列,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
lenDf=len(grades.columns)
n=2
grades.drop(columns=grades.columns[lenDf-n:lenDf],inplace=True)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 14 Sam
3 1 15 Harry
4 2 22 Tom
5 2 15 Golu
6 2 27 Harsh
7 2 23 Clara
8 3 34 Amy
9 3 15 Prashant
10 3 27 Aditya
11 3 23 Radheshyam
在上面的例子中,我们已经计算了 dataframe 中的列总数,并将其存储在lenDf变量中。然后,我们使用列表切片从grades.columns 列表中获得最后 n 列。获得最后 n 列的名称后,我们将它传递给 columns 参数,以便从 pandas 数据帧中删除最后 n 列。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
dropna()方法
dropna() 方法可用于删除具有 nan 值的列。它具有以下语法。
DataFrame.dropna(*, axis=0, how=_NoDefault.no_default, thresh=_NoDefault.no_default, subset=None, inplace=False)
这里,
axis参数用于决定我们是否想要删除具有 nan 值的行或列。默认情况下,axis设置为 0。因此,当在数据帧上执行dropna()方法时,带有 nan 值的行将被删除。要删除具有 nan 值的列,可以将axis参数设置为 1。how参数用于确定需要删除的列是否应该包含所有的值NaN,或者是否可以因为包含至少一个NaN值而将其删除。默认情况下,how参数设置为“any”。因此,即使只存在一个 nan,也将从数据帧中删除该列。- 当我们希望删除至少有特定数量的非 NaN 值的列时,使用
thresh参数。例如,如果您想要删除一个少于 n 个非 NaN 值的列,您可以将数字 n 传递给thresh参数。 - 当我们想要检查每一列的特定索引中的
NaN值时,使用subset参数。默认情况下,子集参数设置为None。因此,dropna()方法在所有索引中搜索NaN值。如果希望它只搜索特定行中的 nan 值,可以将行索引传递给subset参数。要检查两行或更多行中的 nan 值,可以将索引列表传递给subset参数。 inplace参数用于决定我们是在删除操作后获得一个新的数据帧,还是想要修改原始数据帧。当inplace被设置为False时,这是它的默认值,原始数据帧不变,dropna()方法在执行后返回修改后的数据帧。要修改原始数据帧,可以将inplace设置为True。
执行后,如果inplace设置为False,则dropna()方法返回修改后的数据帧。否则返回None。
在 Pandas 数据框架中删除带有 NaN 值的列
要删除具有 nan 值的列,可以在输入数据帧上调用dropna() 方法。此外,您需要将axis参数设置为 1。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.dropna(axis=1,inplace=True)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 14 Sam
3 1 15 Harry
4 2 22 Tom
5 2 15 Golu
6 2 27 Harsh
7 2 23 Clara
8 3 34 Amy
9 3 15 Prashant
10 3 27 Aditya
11 3 23 Radheshyam
在上面的例子中,Marks和Grades列在输入数据帧中有NaN值。因此,在执行dropna()方法后,它们已经从数据帧中删除。
删除数据帧中至少有 N 个 NaN 值的列
要删除至少有 n 个 nan 值的列,可以在dropna()方法中使用thresh参数和axis参数。
thresh参数将非 NaN 元素的最小数量作为其输入参数。如果与 thresh 参数中指定的值相比,dataframe 中任何列的非 NaN 值的数量较少,则在执行dropna() 方法后,该列将从 dataframe 中删除。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
lenDf=len(grades.index)
n=5
count=lenDf-n+1
grades.dropna(axis=1,inplace=True,thresh=count)
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
在这个例子中,如果一列至少有 n 个 NaN 值,我们需要从数据帧中删除它。因此,如果一个列必须包含在输出数据帧中,它应该至少有(数据帧中的行数-n +1)个非 NaN 值。如果任何列的非 NaN 值小于(dataframe 中的行数-n +1 ),则该列将从数据帧中删除。
使用 pop()方法从数据帧中删除列
pop() 方法可以用来一次从数据帧中删除一列。它具有以下语法。
DataFrame.pop(item)
在 dataframe 上调用pop()方法时,它将一个列名作为输入,并从原始 dataframe 中删除该列。它还将删除的列作为输出返回。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.pop("Marks")
print("The output dataframe is:")
print(grades)
输出:
The input dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
The output dataframe is:
Class Roll Name Grade
0 1 11 Aditya A
1 1 12 Chris A
2 1 14 Sam B
3 1 15 Harry NaN
4 2 22 Tom B
5 2 15 Golu B
6 2 27 Harsh C
7 2 23 Clara B
8 3 34 Amy A
9 3 15 Prashant B
10 3 27 Aditya C
11 3 23 Radheshyam NaN
如果 dataframe 中不存在该列,pop()方法将引发一个 KeyError 异常。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is:")
print(grades)
grades.pop("Height")
print("The output dataframe is:")
print(grades)
输出:
KeyError: 'Height'
这里,“高度”参数不在数据帧中。因此,pop()方法引发了 KeyError 异常。
结论
在本文中,我们讨论了用 Python 从 pandas 数据帧中删除列的不同方法。为此,我们使用了drop()方法、 dropna()方法和pop() 方法。
要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
从 Pandas 数据框架中删除重复的行
原文:https://www.pythonforbeginners.com/basics/drop-duplicate-rows-from-a-pandas-dataframe
Pandas 数据帧用于在 Python 中处理表格数据。数据有时包含可能不需要的重复值。在本文中,我们将讨论使用 drop_duplicates()方法从 pandas 数据帧中删除重复行的不同方法。
drop_duplicates 方法
方法用于从 pandas 数据帧中删除重复的行。它具有以下语法。
DataFrame.drop_duplicates(subset=None, *, keep='first', inplace=False, ignore_index=False)
这里,
subset参数用于比较两行以确定重复行。默认情况下,subset参数设置为无。因此,所有列中的值都用于行中的比较。如果您想只通过一列来比较两行,您可以将列名作为输入参数传递给subset参数。如果您想通过两列或更多列来比较行,您可以将列名列表传递给subset参数。keep参数用于决定我们是否希望在输出数据帧中保留一个重复行。如果我们想删除除第一次出现之外的所有重复行,我们可以将参数keep设置为默认值“first”。如果我们想删除除最后一个重复行之外的所有重复行,我们可以将keep参数设置为“last”。如果我们需要删除所有重复的行,我们可以将keep参数设置为 False。inplace参数用于决定我们是在删除操作后获得一个新的数据帧,还是想要修改原始数据帧。当 inplace 设置为 False(这是其默认值)时,原始数据帧不会更改,drop_duplicates()方法会在执行后返回修改后的数据帧。要改变原始数据帧,可以将 inplace 设置为 True。- 当从数据帧中删除行时,索引的顺序变得不规则。如果要刷新索引,将有序索引从 0 分配到
(length of dataframe)-1,可以将ignore_index设置为 True。
执行后,如果inplace参数设置为 False,drop_duplicates()方法返回一个数据帧。否则,它返回 None。
从 Pandas 数据框架中删除重复的行
要从 pandas 数据帧中删除重复的行,可以在数据帧上调用drop_duplicates()方法。执行后,它返回一个包含所有唯一行的数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df=df.drop_duplicates()
print("After dropping duplicates:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 34 Amy 88 A
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
9 2 27 Harsh 55 C
10 3 15 Lokesh 88 A
After dropping duplicates:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
10 3 15 Lokesh 88 A
在上面的例子中,我们有一个输入数据帧,包含一些学生的班级、名单、姓名、分数和成绩。正如您所看到的,输入数据帧包含一些重复的行。索引 0 和 9 处的行是相同的。类似地,索引 3 和 6 处的行是相同的。在执行了drop_duplicates()方法之后,我们得到了一个熊猫数据帧,其中所有的行都是唯一的。因此,从数据帧中删除索引 6 和 9 处的行,以便索引 0 和 3 处的行变得唯一。
从 Pandas 数据框架中删除所有重复的行
在上面的示例中,保留了每组重复行中的一个条目。如果想从 dataframe 中删除所有重复的行,可以在drop_duplicates() 方法中将keep参数设置为 False。此后,所有具有重复值的行将被删除。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df=df.drop_duplicates(keep=False)
print("After dropping duplicates:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 34 Amy 88 A
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
9 2 27 Harsh 55 C
10 3 15 Lokesh 88 A
After dropping duplicates:
Class Roll Name Marks Grade
1 2 23 Clara 78 B
2 3 33 Tina 82 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
10 3 15 Lokesh 88 A
在本例中,您可以观察到索引 0 和 9 处的行是相同的。类似地,索引 3 和 6 处的行是相同的。当我们在drop_duplicates()方法中将keep参数设置为 False 时,您可以观察到所有具有重复值的行(即索引为 0、3、6 和 9 的行)都从输入数据帧中删除了。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇 MLFlow 教程,里面有代码示例。你可能也会喜欢这篇关于 2023 年 T2 15 款免费数据可视化工具的文章。
从 Pandas 数据帧中删除重复的行
默认情况下,drop_duplicates() 方法返回一个新的数据帧。如果您想改变原始数据帧而不是创建一个新的,您可以在如下所示的drop_duplicates() 方法中将inplace参数设置为 True。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df.drop_duplicates(keep=False,inplace=True)
print("After dropping duplicates:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 34 Amy 88 A
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
9 2 27 Harsh 55 C
10 3 15 Lokesh 88 A
After dropping duplicates:
Class Roll Name Marks Grade
1 2 23 Clara 78 B
2 3 33 Tina 82 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
10 3 15 Lokesh 88 A
在这个例子中,我们已经在 drop_duplicates() 方法中将inplace参数设置为 True。因此,drop_duplicates() 方法修改输入数据帧,而不是创建一个新的。这里,drop_duplicates()方法返回 None。
删除特定列中有重复值的行
默认情况下,drop_duplicates() 方法比较所有列的相似性,以检查重复的行。如果您想基于特定的列比较重复值的行,您可以使用drop_duplicates()方法中的subset参数。
subset参数将一列作为它的输入参数。此后,drop_duplicates() 方法只根据指定的列比较行。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df.drop_duplicates(subset=["Class","Roll"],inplace=True)
print("After dropping duplicates:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 34 Amy 88 A
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
9 2 27 Harsh 55 C
10 3 15 Lokesh 88 A
After dropping duplicates:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
7 3 23 Radheshyam 78 B
8 3 11 Bobby 50 D
在这个例子中,我们将 python 列表 ["Class "," Roll"]传递给了drop_duplicates()方法中的subset参数。因此,仅根据这两列来确定重复行。因此,在Class和Roll列中具有相同值的行被认为是重复的,并从数据帧中删除。
结论
在本文中,我们讨论了使用drop_duplicates()方法从数据帧中删除重复行的不同方法。
要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中从系列中删除元素
原文:https://www.pythonforbeginners.com/basics/drop-elements-from-a-series-in-python
Pandas 系列对于处理具有有序键值对的数据非常有用。在本文中,我们将讨论从熊猫系列中删除元素的不同方法。
使用 Drop()方法从熊猫系列中删除元素
我们可以使用drop()方法从熊猫系列中删除元素。它具有以下语法。
Series.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
这里,
labels参数获取我们需要从序列中删除的元素的索引。您可以将单个索引标签或一个索引列表传递给labels参数。axis参数用于决定我们是否要删除一行或一列。对于熊猫系列,不使用axis参数。在函数中定义它只是为了确保drop()方法与熊猫数据帧的兼容性。index参数用于为数据帧中的给定标签选择要删除的元素的索引。index参数对于系列对象是多余的。但是,您可以使用index参数代替labels参数。columns参数用于选择数据帧中要删除的列。“columns”参数在这里也是多余的。您可以使用labels或index参数从系列中删除元素。- 当序列包含多索引时,
levels参数用于从序列中删除元素。levels参数获取需要为指定标签删除元素的级别或级别列表。 - 默认情况下,
drop()方法在从原始序列中删除元素后返回一个新的序列对象。在此过程中,原始系列不会被修改。如果您想要修改原始系列而不是创建新系列,您可以将inplace参数设置为 True。 drop()方法在从序列中删除元素时遇到错误时会引发异常。例如,如果我们想要删除的索引或标签在序列中不存在,那么drop()方法会引发一个 python KeyError 异常。要在从序列中删除元素时抑制此类错误,您可以将 errors 参数设置为“ignore”。
执行后,如果inplace参数设置为 False,drop()方法将返回一个新的序列。否则,它返回 None。
从熊猫系列中删除一个元素
要从序列中删除单个元素,可以将元素的索引传递给 drop()方法中的labels参数,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series=series.drop(labels=11)
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
3 a
23 b
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在上面的例子中,我们首先使用Series()构造函数创建了一个 Series 对象。然后我们使用drop()方法删除索引为 11 的元素。为此,我们将值 11 传递给了drop()方法。在执行了drop()方法之后,您可以观察到索引为 11 的元素已经从输出序列中删除了。
除了labels参数,您还可以在如下所示的drop()方法中使用index参数。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series=series.drop(index=11)
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
3 a
23 b
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在本例中,我们使用了index参数,而不是labels参数。然而,在两种情况下,执行drop()方法后的结果序列是相同的。
从熊猫系列中删除多个元素
要从一个序列中删除多个元素,可以向参数labels传递一个要删除的元素索引的 python 列表。例如,如果您想要删除给定序列中索引 11、16 和 2 处的元素,您可以将列表[11,16,2]传递给drop()方法中的labels参数,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series=series.drop(labels=[11,16,2])
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
3 a
23 b
14 ab
45 bc
65 d
dtype: object
在这个例子中,我们将列表[11, 16, 2]作为输入传递给了参数labels。因此,在执行了drop()方法之后,索引 11、16 和 2 处的元素将从原来的 series 对象中删除。
您可以将索引列表传递给index参数,而不是传递给labels参数,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series=series.drop(index=[11,16,2])
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
3 a
23 b
14 ab
45 bc
65 d
dtype: object
将熊猫系列中的元素放到适当的位置
默认情况下,drop()方法返回一个新的序列,并且不会从原始序列中删除指定的元素。要从 pandas 系列中删除元素,可以将参数inplace设置为 True,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series.drop(index=[11,16,2],inplace=True)
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
3 a
23 b
14 ab
45 bc
65 d
dtype: object
在所有前面的例子中,drop()方法返回一个新的 Series 对象。在这个例子中,我们已经在drop()方法中将inplace参数设置为 True。因此,从原始系列中删除元素,并对其进行修改。在这种情况下, drop()方法返回 None。
如果索引存在,则从序列中删除元素
当使用drop()方法从序列中删除元素时,我们可能会向标签或索引参数传递一个不在序列对象中的索引。如果传递给标签或索引参数的值在序列中不存在,drop() 方法会遇到一个 KeyError 异常,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series.drop(index=1117,inplace=True)
print("The modified series is:")
print(series)
输出:
KeyError: '[1117] not found in axis'
在上面的例子中,我们已经将值1117传递给了参数index。由于值 1117 在序列中不存在,我们得到一个 KeyError 异常。
如果索引存在,为了避免错误并删除序列中的元素,可以使用errors参数。默认情况下,errors参数设置为"raise"。因此,drop() 方法每次遇到错误时都会引发一个异常。为了抑制异常,可以将错误参数设置为“ignore” ,如下例所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series.drop(index=1117,inplace=True,errors="ignore")
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在上面的例子中,我们已经将值1117传递给了 index 参数。因为 1117 不在序列索引中,所以drop()方法会遇到一个 KeyError 异常。然而,我们已经在drop()方法中将errors参数设置为 "ignore"。因此,它抑制了误差。您还可以观察到,drop()方法返回的序列与原始序列相同。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
从熊猫系列中删除 NaN 值
NaN 值是 Python 中具有浮点数据类型的特殊数字。NaN 值用于表示没有值。大多数情况下,NaN 值在给定的数据集中并不重要,我们需要删除这些值。
您可以使用dropna()方法从 pandas 系列中删除 NaN 值。它具有以下语法。
Series.dropna(*, axis=0, inplace=False, how=None)
这里,
axis参数用于决定我们是否要从序列的行或列中删除 nan 值。对于熊猫系列,不使用axis参数。定义它只是为了确保dropna()方法与 pandas 数据帧的兼容性。- 默认情况下,
dropna()方法在从原始系列中删除 nan 值后返回一个新的系列对象。在此过程中,原始系列不会被修改。如果您想从原始序列中删除 nan 值,而不是创建一个新序列,您可以将inplace参数设置为 True。 “how”参数不用于系列。
执行后,如果inplace参数设置为 False,dropna()方法将返回一个新的序列。否则,它返回 None。
您可以从 pandas 系列中删除 nan 值,如下例所示。
import pandas as pd
import numpy as np
letters=["a","b","c",np.nan,"ab","abc",np.nan,"abcd","bc","d"]
series=pd.Series(letters)
print("The original series is:")
print(series)
series=series.dropna()
print("The modified series is:")
print(series)
输出:
The original series is:
0 a
1 b
2 c
3 NaN
4 ab
5 abc
6 NaN
7 abcd
8 bc
9 d
dtype: object
The modified series is:
0 a
1 b
2 c
4 ab
5 abc
7 abcd
8 bc
9 d
在上面的示例中,您可以观察到原始系列有两个 NaN 值。执行后,dropna() 方法删除 NaN 值及其索引,并返回一个新的序列。
从熊猫系列中删除 NaN 值
如果您想从原始序列中删除 NaN 值,而不是创建一个新序列,您可以在如下所示的dropna()方法中将inplace参数设置为 True。
import pandas as pd
import numpy as np
letters=["a","b","c",np.nan,"ab","abc",np.nan,"abcd","bc","d"]
series=pd.Series(letters)
print("The original series is:")
print(series)
series.dropna(inplace=True)
print("The modified series is:")
print(series)
输出:
import pandas as pd
import numpy as np
letters=["a","b","c",np.nan,"ab","abc",np.nan,"abcd","bc","d"]
series=pd.Series(letters)
print("The original series is:")
print(series)
series.dropna(inplace=True)
print("The modified series is:")
print(series)
这里,我们已经将inplace参数设置为 True。因此,dropna()方法修改了原始序列,而不是创建一个新序列。在这种情况下,dropna()方法在执行后返回 None。
从熊猫系列中删除副本
我们数据预处理,我们经常需要从给定的数据中删除重复值。要删除 pandas 系列中的重复值,可以使用drop_duplicates() 方法。它具有以下语法。
Series.drop_duplicates(*, keep='first', inplace=False)
这里,
keep参数用于决定在删除重复项后我们需要保留哪些值。要删除除第一次出现之外的所有重复值,可以将参数keep设置为默认值“first”。要删除除最后一次出现之外的所有重复值,您可以将keep参数设置为“last”。如果想丢弃所有重复值,可以将keep参数设置为 False。- 默认情况下,
drop_duplicates()方法在从原始序列中删除重复值后返回一个新的序列对象。在此过程中,原始系列不会被修改。如果您想删除原始序列中的重复值,而不是创建一个新序列,您可以将inplace参数设置为 True。
执行后,如果inplace参数设置为 False,drop_duplicates()方法将返回一个新的序列。否则,它返回 None。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
letters=["a","b","a","a","ab","abc","ab","abcd","bc","abc","ab"]
series=pd.Series(letters)
print("The original series is:")
print(series)
series=series.drop_duplicates()
print("The modified series is:")
print(series)
输出:
The original series is:
0 a
1 b
2 a
3 a
4 ab
5 abc
6 ab
7 abcd
8 bc
9 abc
10 ab
dtype: object
The modified series is:
0 a
1 b
4 ab
5 abc
7 abcd
8 bc
dtype: object
在上面的示例中,您可以观察到字符串“a”、“ab”和“abc”在序列中出现了多次。因此,当我们在 series 对象上调用drop_duplicates() 方法时,除了字符串的一次出现之外,所有的重复都将从 series 中删除。
查看索引,您可以看到,如果元素在序列中出现多次,则保留了元素的第一次出现。如果希望保留最后出现的具有重复值的元素,可以将keep参数设置为 "last",如下所示。
import pandas as pd
import numpy as np
letters=["a","b","a","a","ab","abc","ab","abcd","bc","abc","ab"]
series=pd.Series(letters)
print("The original series is:")
print(series)
series=series.drop_duplicates(keep="last")
print("The modified series is:")
print(series)
输出:
The original series is:
0 a
1 b
2 a
3 a
4 ab
5 abc
6 ab
7 abcd
8 bc
9 abc
10 ab
dtype: object
The modified series is:
1 b
3 a
7 abcd
8 bc
9 abc
10 ab
dtype: object
在上面的例子中,我们已经将 keep 参数设置为"last"。因此,您可以观察到drop_duplicates() 方法保留了具有重复值的元素的最后一次出现。
在熊猫系列中放置副本
默认情况下,drop_duplicates() 方法不会修改原始的 series 对象。它返回一个新系列。如果您想通过删除重复序列来修改原始序列,您可以在如下所示的drop_duplicates() 方法中将inplace参数设置为 True。
import pandas as pd
import numpy as np
letters=["a","b","a","a","ab","abc","ab","abcd","bc","abc","ab"]
series=pd.Series(letters)
print("The original series is:")
print(series)
series.drop_duplicates(inplace=True)
print("The modified series is:")
print(series)
输出:
The original series is:
0 a
1 b
2 a
3 a
4 ab
5 abc
6 ab
7 abcd
8 bc
9 abc
10 ab
dtype: object
The modified series is:
0 a
1 b
4 ab
5 abc
7 abcd
8 bc
dtype: object
在这个例子中,我们已经将inplace参数设置为真。因此,drop_duplicates() 方法修改了原始序列,而不是创建一个新序列。在这种情况下,d rop_duplicates()方法在执行后返回 None。
删除熊猫系列中的所有重复值
要删除熊猫系列中的所有副本,可以将参数keep设置为 False,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","a","a","ab","abc","ab","abcd","bc","abc","ab"]
series=pd.Series(letters)
print("The original series is:")
print(series)
series=series.drop_duplicates(keep=False)
print("The modified series is:")
print(series)
输出:
The original series is:
0 a
1 b
2 a
3 a
4 ab
5 abc
6 ab
7 abcd
8 bc
9 abc
10 ab
dtype: object
The modified series is:
1 b
7 abcd
8 bc
dtype: object
在这个例子中,我们已经在 drop_duplicates()方法中将keep参数设置为 False。因此,您可以看到所有具有重复值的元素都从序列中删除了。
结论
在本文中,我们讨论了从熊猫系列中删除元素的不同方法。要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
从 Pandas 数据框架中删除行
原文:https://www.pythonforbeginners.com/basics/drop-rows-from-pandas-dataframe
在 Python 中,我们使用 pandas 数据帧来完成许多数据处理任务。有时,由于各种原因,我们需要从数据帧中删除一些行。在本文中,我们将讨论使用drop()方法从 pandas 数据帧中删除行的不同方法。
drop()方法
d rop()方法可以用来从 pandas 数据帧中删除列或行。它具有以下语法。
DataFrame.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
这里,
- 当我们必须从数据帧中删除一行时,使用
index参数。index参数将必须删除的一个索引或索引列表作为其输入参数。 - 当我们需要从数据帧中删除一列时,使用
columns参数。columns参数将需要删除的列名或列名列表作为其输入参数。 labels参数表示我们需要从数据帧中移除的索引或列标签。为了从数据帧中删除行,我们使用索引标签。为了删除两行或更多行,我们还可以向参数labels传递一个索引列表。- 当我们不使用
index参数时,我们可以将需要删除的行的索引传递给labels参数作为它的输入参数。在这种情况下,我们使用axis参数来决定是删除一行还是一列。如果我们想从数据帧中删除一列,我们将axis参数设置为 1。当我们想从数据帧中删除一行时,我们将axis参数设置为 0,这是它的默认值。 - 当我们有多级索引时,
level参数用于从数据帧中删除行。level参数接受我们要从数据帧中删除的行的索引级别或索引名称。要删除两个或更多级别,可以将索引级别或索引名称的列表传递给level参数。 inplace参数用于决定我们是在删除操作后获得一个新的数据帧,还是想要修改原始数据帧。当inplace被设置为 False(这是它的默认值)时,原始的数据帧不变,并且drop()方法在执行后返回修改后的数据帧。要修改原始数据帧,您可以将inplace设置为 True。errors参数用于决定我们是否希望在执行drop()方法时引发异常和错误。默认情况下,errors参数设置为“raise”。因此,如果执行过程中出现任何问题,drop()方法就会引发异常。如果不希望出现错误,可以将错误参数设置为“ignore”。在这之后,drop()方法将抑制所有的异常。
执行后,如果inplace参数设置为 False, drop()方法返回一个新的数据帧。否则,它修改原始数据帧并返回None。
通过索引标签从 Pandas 数据帧中删除行
为了通过索引标签删除数据帧的列,我们将把索引标签传递给drop()方法中的labels参数。执行后,drop()方法将返回一个数据帧,其中包含除了带有在labels参数中指定的索引标签的行之外的所有行。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
print("After dropping rows with index 55")
df=df.drop(labels=55)
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping rows with index 55
The modified dataframe is:
Class Roll Name Grade
Marks
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
78 3 23 Radheshyam B
50 3 11 Bobby D
在上面的例子中,我们已经使用 csv 文件创建了一个数据帧。然后,我们删除了数据帧中索引为 55 的行。在输出数据帧中,您可以观察到索引为 55 的所有行都不存在。因此,drop()方法删除了具有指定索引的行。
除了使用labels参数,您还可以在drop()方法中使用index参数从数据帧中删除一行,如下例所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
print("After dropping rows with index 55")
df=df.drop(index=55)
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping rows with index 55
The modified dataframe is:
Class Roll Name Grade
Marks
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
78 3 23 Radheshyam B
50 3 11 Bobby D
在上面的例子中,我们使用了index参数而不是labels参数来传递索引值作为drop()方法的输入。您可以观察到两种情况下的输出是相同的。因此,您可以使用任何一个index或labels参数从 pandas 数据帧中删除行。
按位置从 Pandas 数据帧中删除行
要按位置从数据帧中删除行,我们将使用以下步骤。
- 首先,我们将使用
index属性获取数据帧的索引对象。 - 接下来,我们将使用 indexing 操作符获取索引对象的元素,该元素位于我们要从数据帧中删除的行的位置。这个元素将是我们要删除的行的标签。
- 在获得要删除的行的标签后,我们可以将标签传递给
labels参数,作为drop()方法中的输入参数。
在执行了drop()方法之后,我们将得到如下所示的修改后的数据帧。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
position=3
print("After dropping row at position 3")
idx=df.index[position-1]
df=df.drop(labels=idx)
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping row at position 3
The modified dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
在上面的例子中,您可以看到我们在数据帧的第三个位置删除了该行。这里,第三个位置的行的索引为 82。因此,如果存在索引为 82 的任何其他行,该行也将从输入数据帧中删除。
在上面的例子中,还可以将从 index 对象获得的索引标签传递给drop() 方法中的index参数。程序执行后你会得到同样的结果。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
position=3
print("After dropping row at position 3")
idx=df.index[position-1]
df=df.drop(index=idx)
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping row at position 3
The modified dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
从熊猫数据框中删除第一行
要从数据帧中删除第一行,我们将首先使用 index 属性获取第一行的索引标签。
然后,我们将索引标签传递给drop() 方法中的labels参数,以删除 dataframe 的第一行,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
position=1
print("After dropping first row")
idx=df.index[position-1]
df=df.drop(index=idx)
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping first row
The modified dataframe is:
Class Roll Name Grade
Marks
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
78 3 23 Radheshyam B
50 3 11 Bobby D
在本例中,我们首先使用数据帧索引和索引操作符来获得第一个位置的行的索引标签,即索引 55。然后,我们将索引标签传递给了drop()方法中的index参数。
在输出中,您可以观察到从数据帧中删除了不止一行。这是因为drop()方法通过索引标签来删除行。因此,与第一行具有相同索引的所有行都将从输入数据帧中删除。
从熊猫数据帧中删除最后一行
为了从数据帧中删除最后一行,我们将首先使用len()函数获得数据帧中的总行数。len()函数将 dataframe 作为其输入参数,并返回 dataframe 中的总行数。
在获得总行数之后,我们将使用index属性获得最后一行的索引标签。此后,我们将把索引标签传递给drop() 方法中的labels参数,以删除 dataframe 的最后一行,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
total_rows=len(df)
position=total_rows-1
print("After dropping last row")
idx=df.index[position]
df=df.drop(labels=idx)
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping last row
The modified dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
在本例中,我们删除了输入数据帧的最后一行。同样,如果输入数据帧包含与最后一行具有相同索引的行,所有这样的行也将被删除。
将行放到数据帧中的适当位置
在前面几节给出的示例中,您可以观察到原始数据帧在删除行后没有被修改。相反,一个新的 dataframe 被创建并由drop()方法返回。如果您想修改现有的数据帧而不是创建一个新的数据帧,您可以在如下所示的drop() 方法中将inplace参数设置为 True。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
total_rows=len(df)
position=total_rows-1
print("After dropping last row")
idx=df.index[position]
df.drop(index=idx,inplace=True)
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping last row
The modified dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
在这个例子中,我们已经在drop() 方法中将inplace参数设置为 True。因此,输入数据帧被修改,而不是创建新的数据帧。在这种情况下,drop()方法返回 None。
如果熊猫数据框架中存在索引,则删除行
如果传递给drop()方法的索引标签在 dataframe 中不存在,drop() 方法就会遇到如下所示的 python KeyError 异常。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
print("After dropping row at index 1117")
df.drop(index=1117,inplace=True)
print("The modified dataframe is:")
print(df)
输出:
KeyError: '[1117] not found in axis'
在上面的示例中,我们试图从输入数据帧中删除索引为 1117 的列。索引 1117 不存在于输入数据帧中。因此,drop()方法会遇到一个 KeyError 异常。
默认情况下,如果传递给labels或index参数的索引标签在 dataframe 中不存在,drop()方法会引发 KeyError 异常。为了在索引不存在时抑制异常并在索引存在时删除行,您可以将errors参数设置为“ignore”,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
print("After dropping row at index 1117")
df.drop(index=1117,inplace=True,errors="ignore")
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping row at index 1117
The modified dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
在这个例子中,我们通过在drop()方法中将 errors 参数设置为"ignore"来抑制异常。因此,当传递给标签的索引标签或索引参数在输入数据帧中不存在时,drop() 方法对输入数据帧没有影响。
在 Pandas 数据帧中通过索引标签删除多行
要在 pandas 数据帧中通过索引标签删除多行,您可以将包含索引标签的列表传递给如下所示的drop() 方法。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
indices=[55,88]
print("After dropping rows at indices 55,88")
df.drop(index=indices,inplace=True,errors="ignore")
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping rows at indices 55,88
The modified dataframe is:
Class Roll Name Grade
Marks
78 2 23 Clara B
82 3 33 Tina A
78 3 15 Prashant B
78 3 23 Radheshyam B
50 3 11 Bobby D
在上面的例子中,我们已经将 list [55,88]传递给了drop() 方法中的index参数。因此,索引为 55 和 88 的所有行都将从输入数据帧中删除。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇 MLFlow 教程,里面有代码示例。你可能也会喜欢这篇关于 2023 年 T2 15 款免费数据可视化工具的文章。
从 Pandas 数据框架中按位置删除多行
要从一个数据帧中按位置删除多行,我们将首先使用 python 索引和index属性找到我们想要删除的位置上所有行的索引标签。然后,我们将把索引标签列表传递给drop() 方法中的labels参数,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
positions=[3,4,5]
indices=[df.index[i-1] for i in positions]
print("After dropping rows at positions 3,4,5")
df.drop(labels=indices,inplace=True,errors="ignore")
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping rows at positions 3,4,5
The modified dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
55 3 27 Aditya C
50 3 11 Bobby D
在上面的例子中,我们删除了位置 3、4 和 5 的行。为此,我们使用了列表理解和索引来获取指定位置的索引标签。然后,我们将索引列表传递给drop()方法中的labels参数,以便根据 pandas 数据帧中的位置删除行。
删除熊猫数据帧中的前 N 行
为了删除数据帧的前 n 行,我们将首先使用数据帧的index属性找到前 n 行的索引标签。然后,我们将把索引标签传递给drop()方法,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
n=3
indices=[df.index[i] for i in range(n)]
print("After dropping first 3 rows")
df.drop(index=indices,inplace=True,errors="ignore")
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping first 3 rows
The modified dataframe is:
Class Roll Name Grade
Marks
88 3 34 Amy A
50 3 11 Bobby D
在上面的例子中,我们只删除了熊猫数据帧的前三行。但是,当执行drop()方法时,会删除更多的行。这是因为drop() 方法通过索引删除行。因此,与前三行具有相同索引的所有行将从数据帧中删除。
删除数据帧的最后 N 行
为了删除数据帧的最后 n 行,我们将首先使用len() 函数找到数据帧中的总行数。然后,我们将使用 index 属性和索引操作符找到最后 n 行的索引标签。获得索引标签后,我们将把它们传递给 drop()方法中的labels参数,以删除这些行,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
print("The dataframe is:")
print(df)
total_rows=len(df)
n=3
indices=[df.index[i] for i in range(total_rows-n,total_rows)]
print("After dropping last 3 rows")
df.drop(index=indices,inplace=True,errors="ignore")
print("The modified dataframe is:")
print(df)
输出:
The dataframe is:
Class Roll Name Grade
Marks
55 2 27 Harsh C
78 2 23 Clara B
82 3 33 Tina A
88 3 34 Amy A
78 3 15 Prashant B
55 3 27 Aditya C
78 3 23 Radheshyam B
50 3 11 Bobby D
After dropping last 3 rows
The modified dataframe is:
Class Roll Name Grade
Marks
82 3 33 Tina A
88 3 34 Amy A
在这个例子中,我们只删除了熊猫数据帧的最后三行。但是,当执行drop()方法时,会删除更多的行。这是因为drop() 方法通过索引删除行。因此,将从数据帧中删除与最后三行具有相同索引的所有行。
结论
在本文中,我们讨论了从 pandas 数据帧中删除行的不同方法。要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
在 Pandas 数据帧中删除带有 Nan 值的行
原文:https://www.pythonforbeginners.com/basics/drop-rows-with-nan-values-in-a-pandas-dataframe
清理数据时,处理 nan 值是一项繁琐的任务。在本文中,我们将讨论使用dropna()方法从 pandas 数据帧中删除具有 nan 值的行的不同方法。
dropna()方法
dropna()方法可用于删除 pandas 数据帧中具有 nan 值的行。它具有以下语法。
DataFrame.dropna(*, axis=0, how=_NoDefault.no_default, thresh=_NoDefault.no_default, subset=None, inplace=False)
这里,
axis参数用于决定我们是否想要删除具有 nan 值的行或列。默认情况下,axis参数设置为 0。因此,当在数据帧上执行dropna()方法时,带有 nan 值的行将被删除。“how”参数用于确定需要删除的行是否应该将所有值都作为 NaN,或者是否可以因为至少有一个 NaN 值而将其删除。默认情况下,“how”参数设置为“any”。因此,即使存在单个 nan 值,也将从数据帧中删除该行。- 当我们希望删除至少有特定数量的非 NaN 值的行时,使用
thresh参数。例如,如果您想要删除一个少于 n 个非空值的行,您可以将数字 n 传递给thresh参数。 - 当我们希望只检查每行中特定列的 NaN 值时,使用
subset参数。默认情况下,subset参数设置为无。因此,dropna()方法在所有列中搜索 NaN 值。如果您希望它只在每行的特定列中搜索 nan 值,您可以将列名传递给subset参数。要检查两列或更多列中的 nan 值,可以将列名列表传递给subset参数。 inplace参数用于决定我们是在删除操作后获得一个新的数据帧,还是想要修改原始数据帧。当inplace被设置为 False(这是它的默认值)时,原始数据帧不会改变,dropna()方法在执行后返回修改后的数据帧。要修改原始数据帧,您可以将inplace设置为真。
删除数据帧中任何列中具有 NaN 值的行
要从一个 pandas 数据帧中删除任何一列中有 nan 值的行,可以直接调用输入数据帧上的dropna()方法。执行后,它返回一个修改后的数据帧,其中删除了 nan 值。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df=df.dropna()
print("After dropping NaN values:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
After dropping NaN values:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
3 3.0 34.0 Amy 88.0 A
5 3.0 27.0 Aditya 55.0 C
7 3.0 23.0 Radheshyam 78.0 B
10 3.0 15.0 Lokesh 88.0 A
在上面的示例中,输入数据帧包含许多具有 NaN 值的行。一旦我们在输入数据帧上调用了dropna()方法,它将返回一个没有空值的数据帧。
删除数据帧中所有列中具有 NaN 值的行
默认情况下,如果 dataframe 中至少有一列有 NaN 值,则 dropna()方法会删除其中的行。如果您只想删除所有列中都有 NaN 值的数据帧,可以将dropna()方法中的“how”参数设置为“all”。此后,只有当任何一行中的所有列都包含 NaN 值时,才从数据帧中删除这些行。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df=df.dropna(how="all")
print("After dropping NaN values:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
After dropping NaN values:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
10 3.0 15.0 Lokesh 88.0 A
在这个例子中,我们已经在dropna()方法中将 how 参数设置为"all"。因此,只有那些所有值都为空的行才会从输入数据帧中删除。因此,只有在所有列中具有 NaN 值的两行被从输入数据帧中删除,而不是前面例子中观察到的五行。
删除至少 N 列中具有非空值的行
您可能还想控制每行中 nan 值的数量,而不是一个或全部。为此,您可以使用dropna() 方法中的thresh参数指定输出数据帧中每行非空值的最小数量。在这之后,由dropna()方法返回的输出数据帧将在每一行中包含至少 N 个空值。这里,N 是作为输入参数传递给 thresh 参数的数字。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df=df.dropna(thresh=4)
print("After dropping NaN values:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
After dropping NaN values:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
10 3.0 15.0 Lokesh 88.0 A
在这个例子中,我们在dropna()方法中指定了参数thresh=4。因此,只有那些具有少于 4 个非空值的行才会从输入数据帧中删除。即使一行有一个空值并且有 4 个以上的非空值,它也不会从数据帧中删除。
删除 Pandas 数据帧中至少有 N 个空值的行
您可能希望从输入数据帧中删除具有 N 个以上空值的所有行,而不是在每行中至少保留 N 个非空值。为此,我们将首先使用 columns 属性和len() 函数找到输入数据帧中的列数。接下来,我们将从数据帧的总列数中减去 N。结果数将是我们希望在输出数据帧中出现的最少数量的非空值。因此,我们将把这个数字传递给dropna()方法中的thresh参数。
在执行了dropna() 方法之后,我们将在删除每一行中至少有 n 个空值的所有行之后得到输出数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
N=3
number_of_columns=len(df.columns)
df=df.dropna(thresh=number_of_columns-N+1)
print("After dropping NaN values:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
After dropping NaN values:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
10 3.0 15.0 Lokesh 88.0 A
这个例子只是前一个例子的变体。如果要删除超过 N 个空值的行,需要保留列数为 N+1 或更多非空值的行。这就是我们在这个例子中所做的。
删除 Pandas 中特定列中具有 NaN 值的行
默认情况下, dropna()方法在每行的所有列中搜索 NaN 值。如果您希望仅当数据帧的特定列中有空值时才删除数据帧中的行,您可以在dropna()方法中使用subset参数。
dropna() 方法中的subset参数将一列列名作为其输入参数。此后,dropna()方法只删除指定列中具有空值的行。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df=df.dropna(subset=["Class","Roll","Marks"])
print("After dropping NaN values:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
After dropping NaN values:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
10 3.0 15.0 Lokesh 88.0 A
在这个例子中,我们将列表 ["Class", "Roll", "Marks"]传递给了dropna()方法中的subset参数。因此,dropna()方法仅在数据帧的这些列中搜索 NaN 值。在执行dropna()方法后,这些列中任何具有 NaN 值的行都将从数据帧中删除。如果一行在这些列中有非空值,并且在其他列中有 NaN 值,则不会将其从数据帧中删除。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇 MLFlow 教程,里面有代码示例。你可能也会喜欢这篇关于 2023 年 T2 15 款免费数据可视化工具的文章。
从 Pandas 数据帧中删除具有 NaN 值的行
在前面几节的所有例子中,dropna()方法不修改输入数据帧。每次,它都返回一个新的数据帧。要通过删除 nan 值来修改输入数据帧,可以使用dropna()方法中的inplace参数。当inplace参数设置为真时,dropna()方法修改原始数据帧,而不是创建一个新的数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
df.dropna(inplace=True)
print("After dropping NaN values:")
print(df)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
After dropping NaN values:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
3 3.0 34.0 Amy 88.0 A
5 3.0 27.0 Aditya 55.0 C
7 3.0 23.0 Radheshyam 78.0 B
10 3.0 15.0 Lokesh 88.0 A
在这个例子中,我们已经在dropna()方法中将inplace参数设置为 True。因此,dropna() 方法修改原始数据帧,而不是创建一个新的数据帧。
结论
在本文中,我们讨论了使用dropna()方法从 pandas 数据帧中删除具有 NaN 值的行的不同方法。
要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
用 Python 清空字典
原文:https://www.pythonforbeginners.com/basics/empty-a-dictionary-in-python
我们使用一个 python 字典来存储键值对。有时,我们可能需要从字典中删除键值对。在本文中,我们将讨论通过在 python 中删除字典中的所有键值对来清空字典的不同方法。
使用 pop()方法清空字典
pop()方法用于从字典中删除一个键值对。当在字典上调用该方法时,它将键作为第一个输入参数,并将一个可选的默认值作为第二个输入参数。在执行时,它从字典中删除键及其关联值,并返回如下所示的值。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
myDict.pop(1)
print("The output dictionary is:")
print(myDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The output dictionary is:
{2: 4, 3: 9, 4: 16, 5: 25}
如果字典中不存在这个键,pop()方法返回作为第二个参数传递给它的默认值。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
val = myDict.pop(10, -1)
print("The popped value is:", val)
print("The output dictionary is:")
print(myDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The popped value is: -1
The output dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
如果我们不向pop()方法传递任何默认值,并且字典中不存在这个键,那么pop()方法就会引发KeyError异常,如下所示。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
val = myDict.pop(10)
print("The output dictionary is:")
print(myDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
val = myDict.pop(10)
KeyError: 10
您可以通过使用 python try except 块来避免该异常。
为了使用 pop()方法清空字典,我们将首先使用keys()方法提取字典的键。之后,我们将从字典中删除每个键及其关联值,如下所示。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
key_list = list(myDict.keys())
for key in key_list:
myDict.pop(key)
print("The output dictionary is:")
print(myDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The output dictionary is:
{}
使用 del 语句清空字典
代替pop()方法,我们可以使用 python 中的del语句来清空 python 中的字典。在这种方法中,我们将使用字典的键删除字典中的每个键-值对,如下所示。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
key_list = list(myDict.keys())
for key in key_list:
del myDict[key]
print("The output dictionary is:")
print(myDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The output dictionary is:
{}
使用 clear()方法清空字典
使用clear()方法,我们可以用一条语句清空 python 中的字典。在字典上调用clear()方法时,会删除字典中的所有键值对。这给我们留下了一个空字典,正如您在下面的例子中所看到的。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
myDict.clear()
print("The output dictionary is:")
print(myDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The output dictionary is:
{}
结论
在本文中,我们讨论了 python 中清空字典的三种方法。想了解更多 python 中的字典,可以阅读这篇关于 python 中字典理解的文章。你可能也会喜欢这篇关于用 python 理解列表的文章。
Python 中的异常处理:编写健壮的 Python 程序
在用 python 编写程序时,可能会出现这样的情况:程序进入一种不希望的状态,称为异常,然后退出执行。这可能导致已完成的工作丢失,甚至可能导致内存泄漏。在本文中,我们将看到如何处理这些异常,以便程序可以使用 python 中的异常处理以正常方式继续执行。我们还将看到在 python 中实现异常处理的不同方法。
Python 中有哪些异常?
异常是程序中不希望出现的事件/错误,它会中断程序中语句的执行流程,并在程序本身没有处理异常时停止程序的执行。python 中有一些预定义的异常。我们还可以通过创建继承 python 中异常类的类来定义异常,然后在程序执行期间使用 raise 关键字创建异常,从而声明用户定义的异常。
在下面的程序中,我们创建了一个字典,并尝试使用 python 字典中的键来访问值。这里,在第二个 print 语句中出现了一个错误,因为"c"在字典中不是一个键。遇到错误时,程序将停止执行。
#create a dictionary
myDict={"a":1,"b":2}
#this will print the value
print(myDict["a"])
#this will generate a KeyError exception and program will exit.
print(myDict["c"])
输出:
1
Traceback (most recent call last):
File "<string>", line 6, in <module>
KeyError: 'c'
在上面的代码中,我们可以看到在打印 1 之后,程序在第二条语句处退出,并通知KeyError 已经发生。我们可以处理这个错误,并使用 python try 和except 块生成定制输出。
python 中如何处理异常?
为了处理程序可能产生的异常,我们使用 python try except 并最终在代码中阻塞来执行语句。
try块包含要执行的可能产生错误/异常的代码。except块具有处理 try 块中生成的错误/异常的代码。- finally 块中的
code总是执行,无论 try 块是否产生异常,finally 块都会被执行。
我们编写必须在 try 块中执行的代码。在 except 块中,我们编写代码来处理 try 块生成的异常。在 finally 块中,我们实现那些最终必须执行的代码部分。无论是否生成异常,finally block 总是在 try 和 except block 之后执行。
在下面的代码中,我们使用 try 和 except 块实现了上一个示例中使用的程序,以便在遇到错误时程序正常终止。
try:
#create a dictionary
myDict={"a":1,"b":2}
#this will print the value
print(myDict["a"])
#this will generate a KeyError exception and program will exit from try block
print(myDict["c"])
except:
print("Error Occurred in Program. Terminating.")
输出
1
Error Occurred in Program. Terminating.
在上面的例子中,我们可以看到在 try 块中执行第一个 print 语句后,程序并没有终止。遇到错误后,它执行 except 块中的语句,然后终止。这里我们必须记住,异常发生点之后的 try 块中的语句将不会被执行。
python 中如何处理特定的异常?
为了不同地处理每个异常,我们可以向异常块提供参数。当生成与参数类型相同的异常时,将执行特定块中的代码。
在下面的代码中,我们将专门处理KeyError 异常,其余的异常将由普通的 except 块处理。
try:
#create a dictionary
myDict={"a":1,"b":2}
#this will print the value
print(myDict["a"])
#this will generate a NameError exception and program will exit from try block
print(a)
except(KeyError):
print("Key is not present in the dictionary. proceeding ahead")
except:
print("Error occured. proceeding ahead")
try:
#create a dictionary
myDict={"a":1,"b":2}
#this will print the value
print(myDict["a"])
#this will generate a NameError exception and program will exit from try block
print(myDict["c"])
except(KeyError):
print("Key is not present in the dictionary. Terminating the program")
except:
print("Error occured. Terminating")
输出:
1
Error occured. proceeding ahead
1
Key is not present in the dictionary. Terminating the program
在上面的程序中,我们可以看到KeyError已经通过将它作为参数传递给 except 块进行了特殊处理,其他异常在 python 中的异常处理过程中正常处理。
Python 中异常处理什么时候用 Finally 块?
最后,当程序中的一些语句需要执行时,不管程序中是否产生异常,都会使用块。在完成文件处理或使用网络连接的程序中,程序必须在终止前终止连接或关闭文件。我们将 finally 块放在 try 和 except 块之后。
try:
#create a dictionary
myDict={"a":1,"b":2}
#this will print the value
print(myDict["a"])
#this will generate a NameError exception and program will exit from try block
print(myDict["c"])
except(KeyError):
print("Key is not present in the dictionary. proceeding ahead")
finally:
print("This is the compulsory part kept in finally block and will always be executed.")
输出:
1
Key is not present in the dictionary. proceeding ahead
This is the compulsory part kept in finally block and will always be executed.
在上面的代码中,我们可以看到 try 块引发了一个异常,这个异常由 except 块处理,然后最后执行 finally 块。
Python 中异常处理何时使用 else 块?
当我们需要在成功执行 try 块中的语句后执行某些代码语句时,我们也可以将 else 块与 python try except 块一起使用。在 try 和 except 块之后写入 Else 块。这里,我们必须记住,else 块中生成的错误/异常不是由 except 块中的语句处理的。
try:
#create a dictionary
myDict={"a":1,"b":2}
#this will print the value
print(myDict["a"])
except:
print("I am in except block and will get executed when an exception occurs in try block")
else:
print("I am in else block and will get executed every time after try block is executed successfully.")
输出:
1
I am in else block and will get executed every time after try block is executed successfully.
在上面的程序中,我们可以看到,当 try 块成功执行时,else 块中的代码已经执行。如果 try 块引发异常,那么只有 except 块会被执行。如果 try 块生成异常,那么 else 块中的代码将不会被执行。
如何在 Python 中生成用户定义的异常?
我们还可以通过使用 python 中的异常处理对一些值进行约束。为了生成一个用户定义的异常,我们在满足特定条件时使用“raise”关键字。然后由代码的 except 块处理该异常。
为了创建一个用户定义的异常,我们创建一个具有期望异常名称的类,它应该继承异常类。之后,我们可以根据实现约束的需要在代码中的任何地方引发异常。
#create an exception class
class SmallNumberException (Exception):
pass
try:
#create a dictionary
myDict={"a":1,"b":2}
#this will raise SmallNumberException
if(myDict["a"]<10):
raise SmallNumberException
except(SmallNumberException):
print("The Number is smaller than 10")
输出:
The Number is smaller than 10
在上面的代码中,我们可以看到已经创建了一个用户定义的异常,它继承了 exception 类,并在一个条件语句之后被引发,以检查数字是否小于 10。我们可以在任何地方使用用户定义的异常来为程序中的变量值添加约束。
结论
在本文中,我们学习了 python 中的异常和异常处理。我们还研究了如何在异常处理期间实现 try、except、finally 和 else 块。此外,我们还研究了如何创建自定义的用户定义的错误和异常,以实现对变量的约束。
Python 中的异常处理
原文:https://www.pythonforbeginners.com/error-handling/exception-handling-in-python
概观
在本帖中,我们将介绍 Python 如何处理异常错误。
什么是例外?
异常是在程序执行过程中发生的错误。当发生
错误时,Python 会生成一个可以处理异常,这避免了您的
程序崩溃。
为什么要使用异常?
异常在很多方面都便于处理程序中的错误和特殊情况
。当你认为你的代码会产生错误时,那么
你可以使用异常处理。
引发异常
您可以使用 raise exception
语句在自己的程序中引发异常。
引发异常会中断当前的代码执行,并返回异常
,直到它被处理。
异常错误
下面是 Python 中一些常见的异常错误:
io error
如果文件打不开。
如果 python 找不到模块,则导入错误
当内置操作或函数接收到类型正确但值不合适的参数时,引发 ValueError
当用户点击中断键(通常是 Control-C 或 Delete)时,引发键盘中断
当其中一个内置函数(input()或 raw_input())在没有读取任何数据的情况下遇到
文件结束条件(e of)时,引发 EOFError
异常错误示例
现在,当我们知道一些异常错误意味着什么时,让我们看一些
例子:
尝试使用尽可能少的 Try 块,并尝试通过它们抛出的异常类型来区分失败
条件。
设置异常处理块
要在 Python 中使用异常处理,首先需要有一个除了
之外的总括子句。
单词“try”和“except”是 Python 关键字,用于捕捉异常。
try-exception【异常名称】(见上例) blocks
try 子句中的代码将逐个语句地执行。
如果出现异常,将跳过 try 块的剩余部分,并执行
except 子句。
try:
some statements here
except:
exception handling
Let's see a short example on how to do this:
try:
print 1/0
except ZeroDivisionError:
print "You can't divide by zero, you're silly."
它是如何工作的?
错误处理是通过使用在 try
块中捕获并在 except 块中处理的异常来完成的。如果遇到错误,try 块
代码执行停止,并向下转移到 except 块。
除了在 try 块后使用 except 块,还可以使用
finally 块。
无论异常
是否发生,finally 块中的代码都将被执行。
代码示例
让我们写一些代码来看看在你的
程序中不使用错误处理时会发生什么。
这个程序会要求用户输入一个 1 到 10 之间的数字,然后打印出
这个数字。
number = int(raw_input("Enter a number between 1 - 10"))
print "you entered number", number
只要用户输入一个数字,这个程序就会非常有趣,但是如果用户输入其他东西(比如一个字符串)会发生什么呢?
Enter a number between 1 - 10
hello
你可以看到,当我们输入一个字符串时,程序抛出了一个错误。
Traceback (most recent call last):
File "enter_number.py", line 1, in
number = int(raw_input("Enter a number between 1 - 10
"))
ValueError: invalid literal for int() with base 10: 'hello'
ValueError 是一种异常类型。让我们看看如何使用异常处理来修复前面的程序
import sys
print "Lets fix the previous code with exception handling"
try:
number = int(raw_input("Enter a number between 1 - 10"))
except ValueError:
print "Err.. numbers only"
sys.exit()
print "you entered number", number
如果我们现在运行程序,输入一个字符串(而不是一个数字),我们可以看到
得到一个不同的输出。
Lets fix the previous code with exception handling
Enter a number between 1 - 10
hello
Err.. numbers only
Try … except … else 子句try,except 语句中的 else 子句必须跟在所有 except 子句之后,如果 try 子句没有引发
异常,那么
对于必须执行的代码非常有用。
试试:
data = something _ that _ can _ go _ errorIOError:
异常错误处理else:
doing _ different _ exception _ handling
else 子句中的异常不被前面的 except 子句处理。确保 else 子句在 finally 块之前运行。Try … finally 子句finally 子句是可选的。其目的是定义在任何情况下都必须执行的清理行动
尝试:
抬起键盘中断最后:
打印“再见,世界!”
……
再见,世界!
键盘中断
无论
异常是否发生,finally 子句总是在离开 try 语句之前执行。
记住,如果你不在 except 行上指定一个异常类型,它将
捕获所有异常,这是一个坏主意,因为这意味着你的程序将忽略
意外的错误以及 except 块实际准备
处理的错误。更多阅读[http://en.wikibooks.org/wiki/Python_Programming/Exceptions](https://en.wikibooks.org/wiki/Python_Programming/Exceptions)[http://www.linuxjournal.com/article/5821](https://www.linuxjournal.com/article/5821)[http://docs.python.org/2/library/exceptions.html](https://docs.python.org/2/library/exceptions.html)[http://docs.python.org/2/tutorial/errors.html](https://docs.python.org/2/tutorial/errors.html)[http://stackoverflow.com/questions/855759/python-try-else](https://stackoverflow.com/questions/855759/python-try-else)
用 Python 从字符串中提取特定的单词
原文:https://www.pythonforbeginners.com/strings/extract-a-specific-word-from-a-string-in-python
在处理文本数据时,有时我们必须搜索文本中特定单词的出现并提取特定单词。在本教程中,我们将学习在 python 中使用内置的字符串方法和正则表达式从字符串中提取特定单词的不同方法。所以,让我们深入研究一下。
使用 python 中的字符串切片从字符串中提取特定的单词
如果我们知道要从字符串中提取的单词的确切位置,我们可以对字符串执行切片操作,以从字符串中提取所需的单词,如下所示。
search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com"
print("String from which word has to be searched is:")
print(search_string)
print("word to be extracted from string:")
word="writing"
print(word)
#calculate length of the word
lword=len(word)
#suppose we already know the starting index of word writing i.e. 34
extracted_string= search_string[34:34+lword]
print("Extracted word is:")
print(extracted_string)
输出:
String from which word has to be searched is:
I am a python programmer and I am writing this code for pythonforbeginners.com
word to be extracted from string:
writing
Extracted word is:
writing
使用 find()方法从字符串中提取特定的单词。
如果我们想从字符串中提取一个特定的单词,并且我们不知道这个单词的确切位置,我们可以首先使用find() 方法找到这个单词的位置,然后我们可以使用字符串切片来提取这个单词。
当对任何字符串调用find()方法时,该方法将被搜索的字符串作为参数,并将被搜索的输入字符串第一次出现的位置作为输出。如果要搜索的字符串不存在,find()方法返回-1。
在用find()方法找到要提取的单词的位置后,我们可以简单地用 slice 操作提取它,如下。
search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com"
print("String from which word has to be searched is:")
print(search_string)
print("word to be extracted from string:")
word="writing"
print(word)
#calculate length of the word
lword=len(word)
start_index=search_string.find(word)
print("start index of the word in string is:")
print(start_index)
extracted_string= search_string[start_index:start_index+lword]
print("Extracted word is:")
print(extracted_string)
输出:
String from which word has to be searched is:
I am a python programmer and I am writing this code for pythonforbeginners.com
word to be extracted from string:
writing
start index of the word in string is:
34
Extracted word is:
writing
使用 index()方法。
如果我们不知道要提取的单词的确切位置,我们也可以使用 string index() 方法找出单词的确切位置,然后我们可以使用切片来提取单词。
当对任何字符串调用index() 方法时,该方法将被搜索的字符串作为参数,并将被搜索的输入字符串第一次出现的位置作为输出。如果要搜索的字符串不存在,index()抛出异常。为此,我们将不得不使用 python try except 来处理异常,同时使用index()方法。
我们可以使用 index()方法和字符串切片从 python 中的字符串中提取一个特定的单词,如下所示。
search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com"
print("String from which word has to be searched is:")
print(search_string)
print("word to be extracted from string:")
word="writing"
print(word)
#calculate length of the word
lword=len(word)
try:
start_index=search_string.index(word)
print("start index of the word in string is:")
print(start_index)
extracted_string= search_string[start_index:start_index+lword]
print("Extracted word is:")
print(extracted_string)
except:
print("word not found")
输出:
String from which word has to be searched is:
I am a python programmer and I am writing this code for pythonforbeginners.com
word to be extracted from string:
writing
start index of the word in string is:
34
Extracted word is:
writing
使用正则表达式提取任何特定的单词
我们可以使用 python 中的正则表达式从字符串中提取特定的单词。我们可以使用来自re模块的search()方法来找到该单词的第一个出现,然后我们可以使用切片来获得该单词。
re.search()方法将以正则表达式形式提取的单词和字符串作为输入 and,并返回一个包含单词起始和结束索引的re.MatchObject。如果没有找到给定的单词,re.search()将返回None。在获得要提取的单词的索引后,我们可以使用字符串切片来提取它,如下所示。
import re
search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com"
print("String from which word has to be searched is:")
print(search_string)
print("word to be extracted from string:")
word=r"writing"
print(word)
#calculate length of the word
lword=len(word)
start_index=re.search(word,search_string).start()
print("start index of the word in string is:")
print(start_index)
extracted_string= search_string[start_index:start_index+lword]
print("Extracted word is:")
print(extracted_string)
输出:
String from which word has to be searched is:
I am a python programmer and I am writing this code for pythonforbeginners.com
word to be extracted from string:
writing
start index of the word in string is:
34
Extracted word is:
writing
结论
在本文中,我们看到了如何使用不同的字符串方法和正则表达式找到字符串中的任何特定单词,然后使用 python 中的字符串切片打印出这个单词。我们也可以使用 python string split 操作来搜索单词是否存在,因为单词是用空格分隔的。请继续关注更多内容丰富的文章。
用 Python 从字符串中提取唯一字符
原文:https://www.pythonforbeginners.com/basics/extract-unique-characters-from-string-in-python
在 Python 中,字符串被广泛用于文本分析。本文讨论如何在 Python 中从字符串中提取唯一字符。
使用 for 循环从 Python 中的字符串提取唯一字符
为了使用 for 循环从字符串中提取唯一的字符,我们将首先定义一个空列表来存储输出字符。然后,我们将使用 for 循环遍历字符串字符。迭代时,我们将检查当前字符是否在列表中。如果是,我们将移动到下一个字符。否则,我们将使用append()方法将当前字符添加到列表中。在列表上调用 append()方法时,该方法将字符作为其输入参数,并将其附加到列表的末尾。
在执行 for 循环后,我们将在列表中获得字符串的所有唯一字符。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=[]
for character in myStr:
if character not in output:
output.append(character)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'F', 'r', 'B', 'e', 'g', 'i', 's']
在上面的例子中,我们使用了字符串“Python For 初学者”。在执行 for 循环之后,我们从字符串中获得唯一字符的列表。
使用集合从 Python 中的字符串提取唯一字符
Python 集合数据结构用于将唯一的不可变对象存储在一起。因为 python 字符串和单个字符都是不可变的,所以我们可以使用集合从 Python 中的字符串中提取字符。
为了在 Python 中从字符串中提取唯一的字符,我们将首先创建一个空集。然后,我们将使用 for 循环遍历字符串字符。迭代时,我们将使用add() 方法将当前字符添加到集合中。在集合上调用add()方法时,该方法将字符作为其输入参数,如果该字符不在集合中,则将它添加到集合中。
在执行 for 循环之后,我们将获得字符串集合中的所有唯一字符。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=set()
for character in myStr:
output.add(character)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: {'F', 'e', 'y', 't', 'h', 'P', 'i', 'g', ' ', 'o', 's', 'r', 'n', 'B'}
除了使用 for 循环和add()方法,您还可以在集合上使用update()方法从 Python 中的字符串中提取唯一的字符。在 set 对象上调用update()方法时,该方法将 iterable 对象作为其输入参数。执行后,它将 iterable 对象的所有元素添加到集合中。由于字符串是一个可迭代的对象,您可以使用update()方法从字符串中提取唯一的字符。
为了使用update()方法从字符串中提取唯一的字符,我们将首先使用set()函数创建一个空集。然后,我们将在空集上调用update()方法,并将字符串作为输入参数传递给update()方法。执行后,我们将得到一个包含字符串所有唯一字符的集合。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=set()
output.update(myStr)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: {'F', 'e', 'y', 't', 'h', 'P', 'i', 'g', ' ', 'o', 's', 'r', 'n', 'B'}
您也可以直接将输入字符串传递给set()函数,以创建一组字符串的唯一字符,如下所示。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=set(myStr)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: {'F', 'e', 'y', 't', 'h', 'P', 'i', 'g', ' ', 'o', 's', 'r', 'n', 'B'}
建议阅读:用 Python 创建聊天应用
使用 Counter()方法从 Python 中的字符串中提取唯一字符
通过所有独特的字符,您还可以找到字符串中字符的频率。您可以使用 collections 模块中定义的 Counter 函数来执行此任务。
Counter()函数将一个 iterable 对象作为其输入参数,并返回一个 Counter 对象。计数器对象包含 iterable 对象的所有独特元素及其频率。
为了从一个字符串中提取所有独特的字符及其频率,我们将把这个字符串作为输入传递给Counter()方法。执行后,我们将获得字符串的所有唯一字符及其频率。您可以在下面的示例中观察到这一点。
from collections import Counter
myStr="Python For Beginners"
print("The input string is:",myStr)
output=Counter(myStr)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: Counter({'n': 3, 'o': 2, ' ': 2, 'r': 2, 'e': 2, 'P': 1, 'y': 1, 't': 1, 'h': 1, 'F': 1, 'B': 1, 'g': 1, 'i': 1, 's': 1})
结论
在本文中,我们讨论了在 Python 中从字符串中提取唯一字符的不同方法。
要了解更多关于 python 编程的知识,你可以阅读这篇关于字符串操作的文章。您可能也会喜欢这篇关于 python simplehttpserver 的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
Python 中数字的因子
原文:https://www.pythonforbeginners.com/basics/factors-of-a-number-in-python
您可能听说过 Python 中的倍数和因数。如果你正在读这个博客,我可以肯定地告诉你,你正在寻找写一个程序,寻找一个数字的因素。在这篇文章中,我们将讨论并实现一个用 python 寻找数字因子的程序。
什么是数的因数?
如果一个数 N 能整除 M,则称它是另一个数 M 的因数。换句话说,如果给我们两个数 N 和 M,M 除以 N 后没有余数,那么 N 称为 M 的因数。你还可以很容易地发现,一个数的任何因数总是小于或等于该数本身。
例如,5 是 20 的因数,因为 20 除以 5 得到的输出是 4,没有余数。
如何在 Python 中求一个数的因子?
为了求一个数 M 的因子,我们可以用 1 到 M 的数来除 M,在除 M 的时候,如果一个数 N 没有余数,我们就说 N 是 M 的因子,为此,我们可以使用 python 中的 For 循环如下。
factors = set()
M = 120 # number whose factors we need to find
for N in range(1, M + 1):
if M % N == 0: # remainder is zero
factors.add(N)
print("Factors of {} are {}".format(M, factors))
输出:
Factors of 120 are {1, 2, 3, 4, 5, 6, 8, 40, 10, 12, 120, 15, 20, 24, 60, 30}
在上面的示例中,我们声明了一个名为 factors 的集合来存储数字 M 的因子。如果任何数字在除以 M 时余数为 0,我们将该数字添加到该集合中。在 for 循环执行之后,我们得到了数字 m 的所有因子的集合。
我们知道,一个数 M 大于 M/2 的唯一因子是 M 本身。因此,我们可以跳过将 M 除以大于 M/2 的数,从而更有效地找到 M 的因子,如下所示。
factors = set()
M = 120 # number whose factors we need to find
factors.add(M) # a number is a factor of itself
for N in range(1, M // 2 + 1):
if M % N == 0: # remainder is zero
factors.add(N)
print("Factors of {} are {}".format(M, factors))
输出:
Factors of 120 are {1, 2, 3, 4, 5, 6, 8, 40, 10, 12, 15, 20, 120, 24, 60, 30}
我们知道一个数的因子成对出现。例如,数量为 M 的因子可以出现在(1,M),(2,M/2),(3,M/3),(4,M/4)对中,直到(M1/2,M^(1/2) )。因此,我们将检查 M^(1/2) 之前的因子,而不是使用 for 循环来检查 M/2 之前的因子。每当我们找到一个因子时,我们也会将它的配对存储在包含所有因子的集合中。这样,我们可以更高效地在 python 中找到一个数的因子。
factors = set()
M = 120 # number whose factors we need to find
factors.add(M) # a number is a factor of itself
for N in range(1, M):
if N * N > M:
break
if M % N == 0: # remainder is zero
factors.add(N)
factors.add(M // N)
print("Factors of {} are {}".format(M, factors))
输出:
Factors of 120 are {1, 2, 3, 4, 5, 6, 40, 8, 10, 12, 15, 20, 120, 24, 60, 30}
结论
在本文中,我们讨论了三个在 python 中寻找数字因子的程序。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。你可能也会喜欢这篇关于 python 中的复数的文章。
从互联网获取数据
原文:https://www.pythonforbeginners.com/python-on-the-web/fetching-data-from-the-internet
什么是 Urllib2?
urllib2 是一个用于获取 URL 的 Python 模块。
我能做什么
它以 urlopen 函数的形式提供了一个非常简单的接口。
Urlopen 能够使用各种不同的协议获取 URL,比如
(http、ftp、file)。
它还提供了一个处理基本认证、cookies、代理
等的接口。
这些是由称为处理程序和打开程序的对象提供的。
HTTP 请求
HTTP 基于请求和响应,客户端发出请求,服务器发送响应。
这个响应是一个类似文件的对象,这意味着您可以调用。阅读()
上的回复。
怎么用?
import urllib2
response = urllib2.urlopen('http://python.org/')
html = response.read()
用户代理
您也可以使用 urllib2 添加自己的头。
有些网站不喜欢被程序浏览。
默认情况下,urllib2 将自己标识为 Python-urllib/x.y(其中 x 和 y 是 Python 版本的主版本号和次版本号,
,这可能会使站点混淆,或者根本不起作用。
浏览器通过用户代理头标识自己。
参见我们的 Urllib2 用户代理帖子,它描述了如何在程序中使用它。
获取 HTTP 头
让我们写一个小脚本,从一个网站获取 HTTP 头。
import urllib2
response = urllib2.urlopen("http://www.python.org")
print "-" * 20
print "URL : ", response.geturl()
headers = response.info()
print "-" * 20
print "This prints the header: ", headers
print "-" * 20
print "Date :", headers['date']
print "-" * 20
print "Server Name: ", headers['Server']
print "-" * 20
print "Last-Modified: ", headers['Last-Modified']
print "-" * 20
print "ETag: ", headers['ETag']
print "-" * 20
print "Content-Length: ", headers['Content-Length']
print "-" * 20
print "Connection: ", headers['Connection']
print "-" * 20
print "Content-Type: ", headers['Content-Type']
print "-" * 20
将给出类似如下的输出:
———————
网址:http://www.python.org
—————
这是打印的标题:日期:Fri,2012 年 10 月 12 日 08:09:40 GMT
服务器:Apache/2.2.16 (Debian)
最后修改时间:周四,2012 年 10 月 11 日 22:36:55 GMT
ETag:" 105800d-4de 0-4c BD 035514 fc0 "【内容
———
日期:Fri,2012 年 10 月 12 日 08:09:40 GMT
————
服务器名:Apache/2 . 2 . 16(Debian)
————
最后修改时间:2012 年 10 月 11 日星期四 22:36:55 GMT
—————
ETag:" 105800d-4de 0-4c bdg
Python 中的斐波那契数列
原文:https://www.pythonforbeginners.com/basics/fibonacci-series-in-python
你可能听说过不同类型的数列。在本文中,我们将讨论这样一个数列,名为斐波那契数列。斐波那契数列在金融市场中有很多重要意义,因为它给出了一个黄金比例,有助于确定任何金融市场的走向。我们还将实现一个用 python 寻找斐波那契数列的程序。
什么是斐波那契数列?
斐波那契数列是以意大利数学家斐波那契的名字命名的。在斐波纳契数列中,位置 N 处的任何数字都被定义为位置(N-1)和(N-2)处的数字之和。
斐波纳契数列的第一项和第二项被定义为 0 和 1。
数学上,斐波纳契数列 F 可以定义如下。
F₁=0
F₂=1
F[N]=F[N-1]+F[N-2]
使用上面的公式,我们可以找到斐波纳契数列中任意位置的数字。举个例子,
F3=F2+F1
=1+0
=1
F4=F3+F2
=1+1
=2
我们可以使用上面的公式找到斐波纳契数列中任意位置的数字。
Python 中如何确定斐波那契数列?
要确定 python 中的斐波那契数列,我们可以简单地使用上面使用的方法。我们可以从第一项和第二项开始,使用 for 循环或 python 中的 while 循环来寻找斐波那契数列中的其他项。
例如,为了找到斐波那契数列中第 N 个位置的数字,我们将执行 while 循环 N-2 次来计算从第 3 个位置到第 N 个位置的项。为了存储这些术语,我们将使用一个 python 列表。
fibonacciList = [0, 1]
# finding 10 terms of the series starting from 3rd term
N = 10
term = 3
while term < N + 1:
value = fibonacciList[term - 2] + fibonacciList[term - 3]
fibonacciList.append(value)
term = term + 1
print("10 terms of the fibonacci series are:")
print(fibonacciList)
输出:
10 terms of the fibonacci series are:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
除了使用 while 循环,我们还可以使用 for 循环来确定 Python 中的斐波那契数列,如下所示。
fibonacciList = [0, 1]
# finding 10 terms of the series starting from 3rd term
N = 10
for term in range(3, N + 1):
value = fibonacciList[term - 2] + fibonacciList[term - 3]
fibonacciList.append(value)
print("10 terms of the fibonacci series are:")
print(fibonacciList)
输出:
10 terms of the fibonacci series are:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
在 Python 中使用递归确定斐波那契数列
你可能知道,如果我们能把问题分解成更小的子问题,我们可以用递归来解决问题。当我们使用斐波纳契数列中的前一项来定义它时,我们可以很容易地创建一个递归解决方案,使用 Python 中的递归来确定斐波纳契数列中任何位置的项。
在递归解决方案中,我们将定义一个函数 Fibonacci(),它将数字 N 作为输入,并返回 Fibonacci 序列中第 N 个位置的项。
对于 N=1,函数返回 0,而对于 N=2,函数返回 1。对于 N 的任何其他值,Fibonacci(N)返回 Fibonacci(N-1)和 Fibonacci(N-2)的和。我们可以用 python 实现这个解决方案,如下所示。
def fibonacci(N):
if N == 1:
return 0
if N == 2:
return 1
return fibonacci(N - 1) + fibonacci(N - 2)
print("10th term of the fibonacci series is:")
print(fibonacci(10))
输出:
10th term of the fibonacci series is:
34
结论
在本文中,我们讨论了斐波那契数列。我们还讨论了在 python 中确定斐波那契数列的方法。要阅读更多关于 python 中数字的内容,你可以阅读这篇关于 python 中十进制数字的文章。你可能也会喜欢这篇关于 python 中的复数的文章。
Python 中的文件处理
原文:https://www.pythonforbeginners.com/filehandling/file-handling-in-python
在实际应用中,我们经常需要从文件中读取数据,并将数据写入文件。在本文中,我们将学习 python 中的文件处理,并将使用 python 中的不同函数实现不同的操作,如 python 读取文件,写入文件和追加文件。
用 Python 打开文件
要在 python 中打开一个文件,我们可以使用 open()函数。通常有两个输入参数传递给 open()函数。第一个参数是需要打开的文件名,第二个参数是打开文件的模式。最常见的模式参数定义如下。
- “r”模式用于以只读模式打开文件。
- “w”模式用于以写模式打开文件。它还会用相同的名称覆盖现有文件,或者创建一个新文件(如果它不存在)。
- “a”模式用于以追加模式打开文件。如果文件不存在,它会创建一个新文件,但如果文件已经存在,它不会覆盖该文件。
- “b”模式用于以二进制模式打开文件。
open()函数在成功打开文件时返回一个 file 对象。可以通过指定文件名和模式打开文件,如下所示。
myFile=open("filename.txt",mode="r")
我们还可以将文件的编码指定为第三个输入参数。默认情况下,编码取决于操作系统。我们可以如下明确指定编码。
myFile=open("filename.txt",mode="r",encoding="UTF-8")
关闭文件
在 python 中,我们必须在程序终止之前使用 close()方法关闭所有打开的文件。对 file 对象调用 close()方法时,会关闭文件。在进行文件操作时,我们必须使用 python try except 进行异常处理,并调用 finally 块中的 close()方法,这样即使在程序执行过程中出现任何错误,文件也会被关闭。打开的文件可以使用 close()方法关闭,如下所示。
myFile.close()
从文件中读取
打开文件后,我们可以使用 read()方法从文件中读取数据。read()方法将一个可选参数作为输入,指定要从文件中读取的字符数。如果在 file 对象上调用 read()方法而不带任何参数,它将读取整个文件并以文本字符串的形式返回。这可以从下面的例子中看出。
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
print(myFile.read())
except Exception as e:
print(str(e))
finally:
myFile.close()
输出:
This is a sample text file.
This file is for PythonForBeginners.com.
This file has been written by Aditya Raj for demonstration.
我们可以从文件中读取一定数量的字符,如下所示。
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
print(myFile.read(21))
except Exception as e:
print(str(e))
finally:
myFile.close()
输出:
This is a sample text
我们也可以使用 readline()方法逐行读取文件,如下所示。
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
print(myFile.readline())
except Exception as e:
print(str(e))
finally:
myFile.close()
输出:
This is a sample text file.
我们还可以使用 for 循环迭代文件。通过这种方式,迭代器逐行迭代文件对象。这可以看如下。
try:
myFile=open("/home/aditya1117/filename.txt",mode="r")
for line in myFile:
print(line)
except Exception as e:
print(str(e))
finally:
myFile.close()
输出:
This is a sample text file.
This file is for PythonForBeginners.com.
This file has been written by Aditya Raj for demonstration.
用 Python 写文件
我们可以使用 write()方法将任何字符串写入打开的文件,如下所示。
try:
myFile=open("/home/aditya1117/filename1.txt",mode="w")
myFile.write("This string is being added to the file.")
except Exception as e:
print(str(e))
finally:
myFile.close()
当文件以“w”模式打开时,它会覆盖现有文件。如果我们想保持以前的数据不变,并向其中添加新数据,我们可以使用“a”表示的追加模式打开文件,如下所示。
try:
myFile=open("/home/aditya1117/filename1.txt",mode="a")
myFile.write("This string is being appended to the file.")
except Exception as e:
print(str(e))
finally:
myFile.close()
结论
在本文中,我们已经理解了 python 中文件处理的概念。我们已经看到了如何打开一个文件,从中读取数据,将数据写入文件,然后关闭文件。请继续关注更多内容丰富的文章。
使用 Python 中的 os 模块进行文件处理
原文:https://www.pythonforbeginners.com/filehandling/file-handling-using-os-module-in-python
在 python 中,您可能已经使用了内置函数来对文件执行操作。在本文中,我们将尝试使用操作系统模块来实现文件处理,以使用 python 中的不同函数来执行文件操作,如 python 读取文件、写入文件和追加文件。
Python 中如何使用 os 模块实现文件处理?
os 模块可用于使用 python 对文件系统执行不同的操作。与内置函数不同,os 模块以字节的形式向文件系统读写数据。像 open()、write()、read()和 close()这样的方法也是在 os 模块中定义的,与内置函数相比具有不同的规范和属性。要使用这些方法,我们可以按如下方式导入 os 模块。
import os
使用操作系统模块打开文件
要使用 os 模块在 python 中打开文件,我们可以使用 open()方法。open()方法接受两个参数作为输入。第一个参数是需要打开的文件名,第二个参数是打开文件的模式。最常见的模式参数定义如下。
- os。O_RDONLY 模式用于以只读模式打开文件。
- os。O_WRONLY 模式用于以只写模式打开文件。
- os。O_RDWR 模式用于打开文件进行读写。
- os。O_APPEND 模式用于以附加模式打开文件,当文件以这种模式打开时,数据在每次写操作时被附加到文件中。
- os。O_CREAT 模式用于创建一个文件,然后在该文件不存在时打开它。
open()方法在成功打开文件时返回一个文件描述符。可以通过指定文件名和模式打开文件,如下所示。
myFile=os.open("filename.txt",os.O_RDONLY)
在管道运算符“|”的帮助下,我们可以在打开文件时同时使用一种或多种模式,如下所示。
myFile=os.open("filename.txt",os.O_RDONLY|os.O_CREAT)
关闭文件
在 python 中,我们必须在程序终止之前关闭所有打开的文件,使用 close()方法来执行成功的写操作。os 模块中的 close()方法也可以用于同样的目的。close()方法将文件描述符作为输入参数,并在成功完成时关闭文件。
在进行文件操作时,我们必须使用 python try except 进行异常处理,并调用 finally 块中的 close()方法,这样即使在文件执行过程中出现任何错误,文件也会被关闭。打开的文件可以使用 close()方法关闭,如下所示。
os.close(myFile)
使用操作系统模块读取文件
我们可以使用 read()方法通过 python 中的 os 模块来读取文件。read()方法将文件描述符作为其第一个参数,将要读取的字节数作为第二个参数,并返回一个字节字符串,需要使用 decode()方法对该字符串进行解码以获得实际数据。
在字节字符串上调用 decode()方法时,它采用要解码的文件的编码类型,并以字符串格式返回数据。
我们可以使用 read()和 decode()方法从文件中读取数据,如下所示。
import os
try:
myFile=os.open("/home/aditya1117/filename.txt",os.O_RDONLY)
myData=os.read(myFile,105)
myStr=myData.decode("UTF-8")
print(myStr)
except Exception as e:
print(str(e))
finally:
os.close(myFile)
输出:
This is a sample text file.
This file is for PythonForBeginners.com.
This file has been written by Aditya
使用操作系统模块写入文件
我们可以使用 write()方法通过 os 模块将数据写入文件系统。write()方法以文件描述符作为第一个参数,以字节格式写入文件的数据作为第二个参数。它从文件描述符的开始处将数据写入文件。成功完成写入操作后,它会返回写入文件的字节数。
为了将我们的数据转换成字节格式,我们将使用 encode()方法。在任何对象上调用 encode()方法时,都将编码格式作为输入,并以字节格式返回数据。
首先,我们将在操作系统中打开文件。O_WRONLY 或 os。O_RDWR 模式,然后我们可以使用 encode()方法和 write()方法,使用 python 中的 os 模块将任何数据写入文件系统,如下所示。
import os
try:
myFile=os.open("/home/aditya1117/filename1.txt",os.O_WRONLY)
myStr="Hi This is Pythonforbeginners.com"
myData=myStr.encode("UTF-8")
os.write(myFile,myData)
except Exception as e:
print(str(e))
finally:
os.close(myFile)
要执行追加操作,我们只需使用 os 打开文件。O_APPEND 与 os 一起。Owronly 模式,然后我们可以使用 write()方法将数据追加到文件中,如下所示。
import os
try:
myFile = os.open("/home/aditya1117/filename2.txt", os.O_WRONLY | os.O_APPEND)
myStr = "Hi! This is Pythonforbeginners.com"
myData = myStr.encode("UTF-8")
os.write(myFile, myData)
except Exception as e:
print(str(e))
finally:
os.close(myFile)
结论
在本文中,我们使用 os 模块在 python 中实现了对文件的不同操作。请继续关注更多内容丰富的文章。
在 Python 中查找字符串中出现的所有子字符串
原文:https://www.pythonforbeginners.com/basics/find-all-occurrences-of-a-substring-in-a-string-in-python
子串是字符串中一个或多个字符的连续序列。在本文中,我们将讨论在 python 中查找一个字符串中所有子字符串的不同方法。
使用 Python 中的 For 循环查找字符串中所有出现的子字符串
在 for 循环的帮助下,我们可以遍历字符串中的字符。要使用 for 循环在 python 中查找一个字符串中所有出现的子字符串,我们将使用以下步骤。
- 首先,我们将找到输入字符串的长度,并将其存储在变量
str_len中。 - 接下来,我们将找到子串的长度,并将其存储在变量
sub_len中。 - 我们还将创建一个名为
sub_indices的列表来存储子字符串出现的起始索引。 - 之后,我们将使用 for 循环遍历输入字符串。
- 在迭代过程中,我们将检查从当前索引开始的长度为
sub_len的子串是否等于输入子串。 - 如果是,我们将使用
append()方法将当前索引存储在sub_indices列表中。当在sub_indices上被调用时,append()方法将当前索引作为其输入参数,并将其附加到sub_indices。
在执行 for 循环之后,我们将获得输入子串在sub_indices列表中所有出现的起始索引。您可以在下面的示例中观察到这一点。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
str_len = len(myStr)
sub_len = len(substring)
sub_indices = []
for i in range(str_len - sub_len):
if myStr[i:i + sub_len] == substring:
sub_indices.append(i)
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
在这里,您可以观察到我们已经获得了子字符串 python 在整个字符串中的起始索引。
使用 Python 中的 While 循环查找字符串中所有出现的子字符串
使用 for 循环迭代字符串中的每个字符在时间上是很昂贵的。它还给出输出中重叠子字符串的索引。为了减少执行时间并在 python 中找到不重叠的子字符串,我们可以使用 while 循环。为此,我们将使用以下步骤。
- 首先,我们将找到输入字符串的长度,并将其存储在变量
str_len中。 - 接下来,我们将找到子串的长度,并将其存储在变量
sub_len中。 - 我们还将创建一个名为
sub_indices的空列表来存储子字符串出现的起始索引和一个初始化为 0 的变量temp。 - 之后,我们将使用 while 循环遍历输入字符串。
- 在迭代过程中,我们将检查从索引
temp开始的长度为sub_len的子串是否等于输入子串。 - 如果是,我们将使用
append()方法将temp存储在sub_indices列表中。然后,我们将温度增加sub_len。 - 如果我们在索引
temp处没有找到所需的子串,我们将把temp加 1。 - 在 while 循环执行之后,我们将获得输入子串在
sub_indices列表中所有出现的起始索引。
您可以在下面的示例中观察到这一点。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
str_len = len(myStr)
sub_len = len(substring)
sub_indices = []
temp = 0
while temp <= str_len - sub_len:
if myStr[temp:temp + sub_len] == substring:
sub_indices.append(temp)
temp = temp + sub_len
else:
temp = temp + 1
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
在这个例子中,我们将只获得输入字符串的所有非重叠子字符串的出现。
使用 Python 中的 Find()方法在字符串中查找子字符串的所有匹配项
在 python 中,find()方法用于查找字符串中任何子串的第一次出现。 find()方法的语法如下。
myStr.find(sub_string, start, end)
这里,
myStr是输入字符串,我们必须在其中找到sub_string的位置。start和end参数是可选的。它们接受字符串的起始索引和结束索引,我们必须在它们之间搜索sub_string。
当我们在一个字符串上调用find()方法时,它将一个子字符串作为它的输入参数。执行后,如果找到子串,它将返回子串的起始索引。否则,它返回-1。您可以在下面的示例中观察到这一点。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
print(myStr.find("python"))
print(myStr.find("Aditya"))
输出:
5
-1
在这里,可以看到find()方法返回子串python的起始索引。另一方面,它为子串aditya返回-1,因为它不在myStr中。
为了使用 python 中的find()方法在一个字符串中找到一个子字符串的所有出现,我们将使用以下步骤。
- 首先,我们将找到输入字符串的长度,并将其存储在变量
str_len中。 - 接下来,我们将找到子串的长度,并将其存储在变量
sub_len中。我们还将创建一个名为sub_indices的列表来存储子字符串出现的起始索引。 - 之后,我们将使用 for 循环遍历输入字符串。
- 在迭代过程中,我们将调用输入字符串上的
find()方法,将子字符串作为第一个输入参数,将当前索引作为第二个输入参数,将当前索引+sub_len作为第三个输入参数。基本上,我们正在检查从 index 到 index+sub_len的当前子串是否是我们正在搜索的字符串。 - 如果
find()方法返回一个非-1 的值,我们将把它附加到sub_indices。这是因为如果在字符串中找到子字符串,find()方法会返回该子字符串的起始索引。然后,我们将转移到 for 循环的下一次执行。 - 如果
find()方法返回-1,我们将转到 for 循环的下一次执行。
在执行 for 循环之后,我们将获得输入子串在sub_indices列表中所有出现的起始索引。您可以在下面的示例中观察到这一点。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
str_len = len(myStr)
sub_len = len(substring)
sub_indices = []
for temp in range(str_len-sub_len):
index = myStr.find(substring, temp, temp + sub_len)
if index != -1:
sub_indices.append(index)
else:
continue
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
同样,上述方法给出了输出中重叠序列的索引。要在 python 中找到一个字符串的非重叠子字符串,我们可以使用 while 循环和如下所示的find() 方法。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
str_len = len(myStr)
sub_len = len(substring)
sub_indices = []
temp = 0
while temp <= str_len - sub_len:
index = myStr.find(substring, temp, temp + sub_len)
if index != -1:
sub_indices.append(index)
temp = temp + sub_len
else:
temp = temp + 1
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
Python 中使用 startswith()方法的字符串中的子字符串
在 python 中,startswith()方法用于查找一个字符串是否以某个子字符串开头。startswith()方法的语法如下。
myStr.startswith(sub_string, start, end)
这里,
myStr是我们必须检查它是否以sub_string开头的输入字符串。start和end参数是可选的。它们接受字符串的起始索引和结束索引,在它们之间我们必须检查字符串是否在索引start处以sub_string开始。
当我们在一个字符串上调用startswith()方法时,它将一个子字符串作为它的输入参数。执行后,如果字符串以子字符串开头,则返回True。否则,它返回 False。您可以在下面的示例中观察到这一点。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
print(myStr.startswith("python"))
print(myStr.startswith("I am"))
输出:
False
True
在这里,您可以观察到子串python的startswith()方法returns为 False。另一方面,它为子串I am返回True。这是因为myStr从 I am开始,而不是从python开始。
为了使用startswith()方法在 python 中找到一个字符串中所有出现的子字符串,我们将使用以下步骤。
- 首先,我们将找到输入字符串的长度,并将其存储在变量
str_len中。 - 接下来,我们将找到子串的长度,并将其存储在变量
sub_len中。我们还将创建一个名为sub_indices的列表来存储子字符串出现的起始索引。 - 之后,我们将使用 for 循环遍历输入字符串。
- 在迭代过程中,我们将调用输入字符串上的
startswith()方法,将子字符串作为第一个输入参数,将当前索引作为第二个输入参数。 - 如果
startswith()方法返回False,这意味着子串没有从当前索引开始。因此,我们将转到 for 循环的下一次执行。 - 如果
startswith()方法返回True,则意味着子串从当前索引开始。因此,我们将把当前索引附加到sub_indices上。之后,我们将进入 for 循环的下一次迭代。
在执行 for 循环之后,我们将获得输入子串在sub_indices列表中所有出现的起始索引。您可以在下面的示例中观察到这一点。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
str_len = len(myStr)
sub_len = len(substring)
sub_indices = []
for temp in range(str_len-sub_len):
index = myStr.startswith(substring, temp)
if index:
sub_indices.append(temp)
else:
continue
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
使用 for 循环的方法给出了子串在字符串中重叠出现的索引。要在 python 中查找子串的非重叠索引的索引,可以使用如下所示的startswith()方法和 while 循环。
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
str_len = len(myStr)
sub_len = len(substring)
sub_indices = []
temp = 0
while temp <= str_len - sub_len:
index = myStr.startswith(substring, temp)
if index:
sub_indices.append(temp)
temp = temp + sub_len
else:
temp = temp + 1
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
使用 Python 中的正则表达式查找字符串中子字符串的所有匹配项
正则表达式为我们提供了一种在 Python 中操作文本数据的最有效的方法。我们还可以使用re模块中提供的finditer() 方法在 python 中找到一个字符串中所有出现的子字符串。finditer()方法的语法如下。
re.finditer(sub_string, input_string)
这里,input_string是一个字符串,我们必须在其中搜索sub_string的出现。
finditer()方法将子字符串作为第一个输入参数,将原始字符串作为第二个参数。执行后,它返回一个迭代器,其中包含子字符串的匹配对象。匹配对象包含有关子字符串的起始和结束索引的信息。我们可以通过对匹配对象调用start() 方法和 end()方法来获得匹配对象的开始和结束索引。
为了使用finditer()方法在 python 中找到一个字符串中所有出现的子字符串,我们将使用以下步骤。
- 首先,我们将创建一个名为
sub_indices的列表来存储子字符串出现的起始索引。 - 之后,我们将获得包含子串匹配对象的迭代器。
- 一旦我们得到迭代器,我们将使用 for 循环遍历匹配对象。
- 迭代时,我们将调用当前匹配对象上的
start()方法。它将返回原始字符串中子串的起始索引。我们将把索引附加到sub_indices上。
在 for 循环执行之后,我们将获得输入字符串中给定子字符串的所有匹配项的起始索引。您可以在以下示例中观察到这一点。
import re
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
sub_indices = []
match_objects = re.finditer(substring, myStr)
for temp in match_objects:
index = temp.start()
sub_indices.append(index)
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
除了使用 for 循环,您还可以使用 list comprehension 在 python 中查找一个字符串中所有出现的子字符串,如下所示。
import re
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
match_objects = re.finditer(substring, myStr)
sub_indices = [temp.start() for temp in match_objects]
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[5, 40, 74]
在上面的例子中,我们首先使用finditer()方法获得了匹配对象。之后,我们使用列表理解和start()方法来寻找myStr中子串的起始索引。
使用 Python 中的使用 flashtext 模块在字符串中出现的所有子字符串
在 Python 中,您可以使用flashtext模块来查找一个字符串中所有出现的子字符串,而不是使用上面讨论的所有方法。您可以使用以下语句通过 PIP 安装flashtext模块。
pip3 install flashtext
要使用 flashtext 模块在一个字符串中查找一个子字符串的所有出现,我们将使用以下步骤。
- 首先,我们将使用
KeywordProcessor()函数创建一个关键字处理器对象。 - 创建关键字处理器后,我们将使用
add_keyword()方法将子串添加到关键字处理器对象中。当在关键字处理器对象上调用add_keyword()方法时,它会将子字符串作为输入参数。 - 然后,我们将调用关键字处理器对象上的
extract_keywords()方法。它返回一个元组列表。每个元组包含子串作为其第一个元素,子串的开始索引作为其第二个元素,结束索引作为其第三个元素。 - 最后,我们将创建一个名为
sub_indices的空列表,并使用 for 循环从元组列表中提取子串的起始索引。
在执行 for 循环之后,我们将在sub_indices中获得输入字符串中给定子串的所有出现的起始索引。您可以在下面的示例中观察到这一点。
from flashtext import KeywordProcessor
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
sub_indices = []
kwp = KeywordProcessor()
kwp.add_keyword(substring)
result_list = kwp.extract_keywords(myStr,span_info=True)
for tuples in result_list:
sub_indices.append(tuples[1])
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[40, 74]
除了在最后一步中使用 for 循环,还可以使用 list comprehension 在 python 中查找某个字符串中某个子字符串的所有匹配项,如下所示。
from flashtext import KeywordProcessor
myStr = "I am pythonforbeginners. I provide free python tutorials for you to learn python."
substring = "python"
kwp = KeywordProcessor()
kwp.add_keyword(substring)
result_list = kwp.extract_keywords(myStr, span_info=True)
sub_indices = [tuples[1] for tuples in result_list]
print("The string is:", myStr)
print("The substring is:", substring)
print("The starting indices of the occurrences of {} in the string are:{}".format(substring, sub_indices))
输出:
The string is: I am pythonforbeginners. I provide free python tutorials for you to learn python.
The substring is: python
The starting indices of the occurrences of python in the string are:[40, 74]
在这种方法中,您可以观察到关键字流程只提取子字符串的两个实例。这是由于关键字处理器搜索整个单词的原因。如果子字符串不是整个单词,它就不会包含在结果中。
结论
在本文中,我们讨论了在 Python 中查找一个字符串中所有子字符串的不同方法。在所有这些方法中,我建议您使用带有列表理解的正则表达式。它会在最快的时间内给你结果,因为这是最有效的方法。
要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中删除列表中所有出现的字符的文章。您可能也喜欢这篇关于如何检查 python 字符串是否包含数字的文章。
请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中求一个数的阶乘
原文:https://www.pythonforbeginners.com/basics/find-factorial-of-a-number-in-python
在数学中,我们可以对任何给定的数进行不同的运算。一个这样的操作是寻找一个数的阶乘。在本文中,我们将讨论什么是阶乘,以及如何在 python 中找到一个数的阶乘。
什么是数的阶乘?
一个数 N 的阶乘定义为从 1 到 N 的所有数的乘积,换句话说,要求给定数 N 的阶乘,我们只需将 1 到 N 的所有数相乘。
例如,5 的阶乘将被计算为1x2x3x4x5,即 120。同样,6 的阶乘将是1x2x3x4x5x6即 720。
0 的阶乘已被定义为 1。另一方面,没有为负整数定义阶乘。
知道了这么多,让我们设计一个算法来寻找一个给定数字的阶乘。
在 Python 中求一个数的阶乘
要找到任意给定数字 N 的阶乘,我们只需将 1 到 N 的所有数字相乘,在此之前,我们将首先检查给定数字是否为负数。如果是,我们将通知用户没有为给定的数字定义阶乘。如果输入数是 0,我们就说阶乘是 1。
在正整数的情况下,我们可以定义一个变量“myFact”,并使用 python 中的 for 循环找到从 1 到 N 的所有数字的乘积,如下所示。
def factorial(N):
if N < 0:
return -1
if N == 0:
return 1
myFact = 1
for i in range(1, N + 1):
myFact = myFact * i
return myFact
input_number = 0
output = factorial(input_number)
if output == -1:
print("Factorial not defined for negative number {}.".format(input_number))
else:
print("Factorial of {} is {}.".format(input_number, output))
input_number = 6
output = factorial(input_number)
if output == -1:
print("Factorial not defined for negative number {}.".format(input_number))
else:
print("Factorial of {} is {}.".format(input_number, output))
input_number = -10
output = factorial(input_number)
if output == -1:
print("Factorial not defined for negative number {}.".format(input_number))
else:
print("Factorial of {} is {}.".format(input_number, output))
输出:
Factorial of 0 is 1.
Factorial of 6 is 720.
Factorial not defined for negative number -10.
或者,我们可以使用 while 循环来寻找阶乘。这里,我们将使用一个计数变量,从 1 开始,一直到 N,在 while 循环的每次迭代中递增 1。在每次迭代中,我们将把计数乘以先前数的乘积。因此,我们可以使用 python 中的 while 循环来计算数字的阶乘,如下所示。
def factorial(N):
if N < 0:
return -1
if N == 0:
return 1
myFact = 1
count = 1
while count <= N:
myFact = myFact * count
count = count + 1
return myFact
input_number = 0
output = factorial(input_number)
if output == -1:
print("Factorial not defined for negative number {}.".format(input_number))
else:
print("Factorial of {} is {}.".format(input_number, output))
input_number = 6
output = factorial(input_number)
if output == -1:
print("Factorial not defined for negative number {}.".format(input_number))
else:
print("Factorial of {} is {}.".format(input_number, output))
input_number = -10
output = factorial(input_number)
if output == -1:
print("Factorial not defined for negative number {}.".format(input_number))
else:
print("Factorial of {} is {}.".format(input_number, output))
输出:
Factorial of 0 is 1.
Factorial of 6 is 720.
Factorial not defined for negative number -10.
结论
在本文中,我们讨论了一个数的阶乘。我们还使用 python 中的 for 循环和 while 循环实现了寻找数字阶乘的程序。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。您可能还会喜欢这篇关于 python 中的复数的文章。
在 Python 中求一个数的质因数
原文:https://www.pythonforbeginners.com/basics/find-prime-factors-of-a-number-in-python
你可能听说过数字的因数。任何给定数的因数都是那些能把给定数整除而不留余数的数。在本文中,我们将讨论一种在 python 中寻找一个数的质因数的算法。
一个数的质因数是什么?
质数是那些只有两个因子的数,1 和数本身。此外,我们可以将任何给定的数表示为质数的乘积。在这里,我们可以用来表示任何一个给定数字的所有那些质数都叫做这个给定数字的质因数。
例如,我们可以将 20 表示为素数 2 的乘积,将 5 表示为 2x2x5。因此,2 和 5 是 20 的质因数。同样,我们可以用质数的组合来表示任何数。
求一个数的质因数的算法
要找出一个数的质因数,我们只需用质数来除给定的数。但是,我们如何知道给定数字的一个因子是否是质数呢?为了消除这个问题,我们将使用重复除法。让我们以数字 1260 为例,这样我们就可以找到它的质因数。
首先,我们将给定的数重复除以 2,并存储结果数,直到余数变为 1。这样,我们将确保任何偶数都不会除以合成数。现在,我们可以跳过所有偶数,同时找到给定数字的因子。例如,我们将 1260 除以 2 两次,得到的结果是 315。在这里,你可以看到结果 315 是一个奇数。因此,没有偶数可以是它的因子。
除以 2 后,我们将重复地将结果除以 3,并存储结果,直到该数不能被 3 除。这样,我们将确保 3 的任何倍数都不会将结果除尽。在这里,我们将 315 除以 3 两次,得到 35 作为结果。可以看到没有 3 的倍数能除以 35。
同样,我们将使用 5、7、9、11 和其他奇数执行重复除法,直到结果变为 1。用这种方法,我们可以找到任何给定数的质因数。这里,1260 的质因数是 2、3、5 和 7。
Python 程序寻找一个数的质因数
现在,我们将实现上面讨论的算法来寻找任何给定数字的质因数。这里,我们将创建一个集合来存储质因数,并如下实现上述算法。
def calculate_prime_factors(N):
prime_factors = set()
if N % 2 == 0:
prime_factors.add(2)
while N % 2 == 0:
N = N // 2
if N == 1:
return prime_factors
for factor in range(3, N + 1, 2):
if N % factor == 0:
prime_factors.add(factor)
while N % factor == 0:
N = N // factor
if N == 1:
return prime_factors
input_number = 20
output = calculate_prime_factors(input_number)
print("Prime factors of {} are {}".format(input_number, output))
input_number = 1260
output = calculate_prime_factors(input_number)
print("Prime factors of {} are {}".format(input_number, output))
输出:
Prime factors of 20 are {2, 5}
Prime factors of 1260 are {2, 3, 5, 7}
结论
在本文中,我们讨论并实现了一个用 python 来寻找给定数字的质因数的算法。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。您可能还会喜欢这篇关于 python 中的复数的文章。
求二叉树的高度
原文:https://www.pythonforbeginners.com/data-structures/find-the-height-of-a-binary-tree
就像我们找到一个列表的长度或者一个 python 字典中的条目数一样,我们可以找到一棵二叉树的高度。在这篇文章中,我们将制定一个算法来寻找二叉树的高度。我们还将用 python 实现该算法,并在给定的二叉树上执行。
二叉树的高度是多少?
二叉树的高度被定义为距离二叉树中节点所在的根节点的最大距离。二叉树的高度取决于节点的数量及其在树中的位置。如果一棵树有“n”个节点,它的高度可以是 log(n) + 1 到 n 之间的任何值。如果该树完全向左或向右倾斜,则二叉树的高度为 n。如果树中的节点适当分布,并且该树是完全二叉树,则它的高度为 log(n)+1。
例如,下面的二叉树有 7 个元素。具有 7 个元素的二叉树可以具有 log(7)+ 1 之间的任何高度,即 3 和 7。在我们的例子中,树的节点是适当分布的,树是完全平衡的。因此,树的高度是 3。

binary tree
如何计算二叉树的高度?
为了计算二叉树的高度,我们可以计算左右子树的高度。子树高度的最大值可以通过加 1 来求树的高度。对于一个空根,我们可以说树的高度为零。类似地,单个节点的高度将被认为是 1。
求二叉树高度的算法
现在我们已经找到了一种方法来寻找高度的二叉树,我们将制定算法来寻找高度如下。
- 如果我们找到一个空的根节点,我们会说树的高度是 0。
- 否则,我们将递归地找到左子树和右子树的高度。
- 找到左子树和右子树的高度后,我们将计算它们的最大高度。
- 我们将在最大高度上加 1。这将是二叉树的高度。
算法在 Python 中的实现
现在我们已经理解并制定了算法,我们将用 Python 实现它。
from queue import Queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def height(root):
if root is None:
return 0
leftHeight=height(root.leftChild)
rightHeight=height(root.rightChild)
max_height= leftHeight
if rightHeight>max_height:
max_height = rightHeight
return max_height+1
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# 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
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
print("Height of the binary tree is:")
print(height(root))
输出:
Height of the binary tree is:
3
这里,我们创建了一个二叉树节点。然后,我们定义了向二叉树插入元素的函数。最后,我们用 Python 实现了求二叉树高度的算法。
结论
在本文中,我们实现了一个算法来寻找二叉树的高度。要了解更多关于其他数据结构的知识,可以阅读这篇关于 Python 中的链表的文章。请继续关注更多关于用 Python 实现不同算法的文章。
查找列表中元素的索引
原文:https://www.pythonforbeginners.com/basics/find-the-index-of-an-element-in-a-list
在一个列表中搜索一个元素的所有出现是一项单调乏味的任务。在本文中,我们将尝试查找列表中某个元素的索引。我们将研究不同的方法来查找列表中元素的第一个、最后一个和其他出现的位置。
使用 index()方法查找列表中元素的索引
我们可以使用 index()方法来查找列表中第一个出现的元素。index()方法将元素作为第一个输入参数,这是必需的。它有两个可选参数,这两个参数是列表中搜索开始和停止的索引。如果输入元素存在于指定索引之间的列表中,则 index()方法返回它第一次出现的元素的索引。我们可以在下面的例子中观察到这一点。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 2
print("List is:", myList)
print("Number is:", myNum)
index = myList.index(myNum)
print("Index of {} is {}".format(myNum, index))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 2
Index of 2 is 1
如果元素不在列表中指定的索引之间,index()方法将引发 ValueError。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 100
print("List is:", myList)
print("Number is:", myNum)
index = myList.index(myNum)
print("Index of {} is {}".format(myNum, index))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 100
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 5, in <module>
index = myList.index(myNum)
ValueError: 100 is not in list
我们可以通过使用除了块之外的 python try 的异常处理来处理ValueError,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 100
print("List is:", myList)
print("Number is:", myNum)
try:
index = myList.index(myNum)
print("Index of {} is {}".format(myNum, index))
except ValueError:
print("{} is not in the list.".format(myNum))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 100
100 is not in the list.
我们可以使用 index()方法找到列表中某个元素的第一个索引,但是我们不能使用它来找到列表中任何元素的所有匹配项。我们将使用 for 循环来迭代列表,以找到列表中任何元素的所有匹配项。
使用 for 循环查找列表中元素的索引
要使用 for 循环查找列表中元素的索引,我们只需遍历列表并检查每个元素。在迭代过程中,如果我们找到了需要找到索引的元素,我们将简单地如下打印索引。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
index = -1 # some invalid value
listLen = len(myList)
for i in range(listLen):
if myList[i] == myNum:
index = i
break
if index == -1:
print("{} not found in the list".format(myNum))
else:
print("Index of {} is {}".format(myNum, index))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Index of 3 is 2
获取列表中最后一个出现的元素
要从元素存在的结尾找到索引,我们可以简单地遍历循环并维护最后找到元素的结果索引。只要找到元素,我们就会更新结果索引。这样,在列表的完整迭代之后,我们将拥有结果索引中元素的最后一个索引。这可以如下进行。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
index = -1 # some invalid value
listLen = len(myList)
for i in range(listLen):
if myList[i] == myNum:
index = i
if index == -1:
print("{} not found in the list".format(myNum))
else:
print("Last index of {} is {}".format(myNum, index))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Last index of 3 is 9
上面的方法要求我们每次都要迭代整个列表,以找到元素在列表中出现的最后一个索引。为了避免这种情况,我们可以从末尾开始向后迭代列表。这里我们将使用索引,在找到元素后,我们将通过将负索引添加到列表的长度来获得元素的正索引,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
index = -1 # some invalid value
listLen = len(myList)
for i in range(-1, -listLen, -1):
if myList[i] == myNum:
index = listLen+i
break
if index == -1:
print("{} not found in the list".format(myNum))
else:
print("Last index of {} is {}".format(myNum, index))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Last index of 3 is 9
获取列表中元素的所有匹配项
要查找列表中某个元素的所有出现,我们可以使用 for 循环遍历列表,并打印该元素在列表中出现的位置的索引,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
indices = []
listLen = len(myList)
for i in range(listLen):
if myList[i] == myNum:
indices.append(i)
if indices is None:
print("{} not found in the list".format(myNum))
else:
print("Indices of {} are {}".format(myNum, indices))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Indices of 3 are [2, 9]
不使用 for 循环,我们可以使用 list comprehension 来查找元素出现的所有索引,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 2
print("List is:", myList)
print("Number is:", myNum)
listLen = len(myList)
indices = [i for i in range(listLen) if myList[i] == myNum]
if indices is None:
print("{} not found in the list".format(myNum))
else:
print("Indices of {} are {}".format(myNum, indices))
输出:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 2
Indices of 2 are [1, 8]
结论
在本文中,我们使用了不同的方法来查找列表中元素的索引。我们还研究了查找列表中所有元素的方法。请继续关注更多内容丰富的文章。
在 Python 中查找列表中最大值的索引
原文:https://www.pythonforbeginners.com/basics/find-the-index-of-max-value-in-a-list-in-python
python 中的列表是最常用的数据结构之一。在本文中,我们将讨论在 python 中查找列表中最大值的索引的不同方法。
在 Python 中使用 for 循环查找列表中最大值的索引
要使用 for 循环查找列表中最大值的索引,我们将使用以下过程。
- 首先,假设第一个元素是列表的最大元素,我们将把变量
max_index初始化为 0。 - 之后,我们将使用
len()函数找到列表的长度。len()函数将一个列表作为其输入参数,并返回列表的长度。 - 一旦我们得到了列表的长度,我们将使用
range()函数和一个 for 循环来遍历列表。迭代时,在列表的每个索引处,我们将检查当前索引处的元素是否大于索引处的元素max_index。 - 如果我们找到一个索引,其中的元素大于索引
max_index处的元素,我们将把当前索引赋给变量max_index。
在整个列表迭代之后,我们将获得变量max_index中最大元素的索引。
您可以在下面的示例中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 21, 12]
print("The list is:", myList)
max_index = 0
list_len = len(myList)
for index in range(list_len):
if myList[index] > myList[max_index]:
max_index = index
print("Index of the maximum element is:", max_index)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 21, 12]
Index of the maximum element is: 7
在上面的例子中,如果最大值元素出现多次,我们得到最大值元素最左边的索引。
为了获得最大元素的最右边的索引,在比较元素时,可以使用大于或等于(>=)操作符,而不是大于(>)操作符,如下所示。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
max_index = 0
list_len = len(myList)
for index in range(list_len):
if myList[index] >= myList[max_index]:
max_index = index
print("Index of the maximum element is:", max_index)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Index of the maximum element is: 9
使用 Max()函数和 Index()方法查找列表中最大值的索引
要编写更 python 化的代码,可以使用max()函数和index()方法在 python 中查找列表中最大值的索引。
max()函数
max() 函数接受一个容器对象,如列表、元组或集合,作为它的输入参数。执行后,它返回容器对象的最大元素。
例如,如果我们给一个列表作为max()函数的输入参数,它将返回列表的最大元素。您可以在下面的示例中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
max_val = max(myList)
print("The maximum value is:", max_val)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
The maximum value is: 55
index()方法
在列表上调用index() 方法时,该方法将一个元素作为其输入参数,并从列表的开始处返回该元素第一次出现的索引。您可以在下面的示例中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
index = myList.index(23)
print("Index of 23 is:", index)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Index of 23 is: 2
当输入元素不在列表中时,index()方法引发一个ValueError异常,表明给定元素不在列表中,如下所示。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
index = myList.index(112)
print("Index of 112 is:", index)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
index = myList.index(112)
ValueError: 112 is not in list
为了在 python 中找到列表中最大值的索引,我们将首先使用max()函数找到列表中的最大元素。之后,我们将调用列表上的index()方法,将最大元素作为其输入参数。在执行了index()方法后,我们将得到列表中最大元素的索引。您可以在下面的示例中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
max_val = max(myList)
index = myList.index(max_val)
print("Index of maximum value is:", index)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Index of maximum value is: 7
这里,最大值 55 出现在两个索引处。然而,index()方法只返回元素最左边出现的索引。
使用 Max()函数和 For 循环查找多次出现的最大值的索引
在使用max()函数和index()方法的方法中,我们只能在 python 中找到列表中最大值的第一个索引。为了在最大值多次出现的情况下找到列表中最大值的索引,我们可以使用下面的方法。
- 首先,我们将使用
max()函数找到列表中的最大值。 - 然后,我们将创建一个名为
list_indices的列表来存储列表中最大值的索引。 - 之后,我们将使用
len()函数找到输入列表的长度。len()函数将列表作为其输入参数,并返回列表的长度。我们将把长度存储在变量list_len中。 - 获得列表长度后,我们将使用
range()函数创建一个从 0 到list_len的数字序列。range()函数将list_len作为其输入参数,并返回一个包含从 0 到list_len-1的数字序列。 - 现在,我们将使用循环的来迭代数字序列。迭代时,我们将检查列表中与序列中当前编号相等的索引处的元素是否等于最大值。
- 如果我们在序列中找到一个索引,在这个索引处有列表中的最大值。我们将使用
append()方法将索引存储在list_indices中。当在列表上调用append()方法时,它将把索引值作为输入参数,并把它添加到列表中。
在执行 for 循环后,我们将获得list_indices中最大值的所有索引。您可以在下面的示例中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
max_val = max(myList)
list_indices = []
list_len = len(myList)
sequence = range(list_len)
for index in sequence:
if myList[index] == max_val:
list_indices.append(index)
print("Indices of maximum element are:", list_indices)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Indices of maximum element are: [7, 9]
在多次出现的情况下,使用 Max()函数和列表理解来查找最大值的索引
不使用 for 循环,您可以使用列表理解以及range()函数和max()函数从给定的输入列表中获取最大值的索引列表,如下所示。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
max_val = max(myList)
list_len = len(myList)
sequence = range(list_len)
list_indices = [index for index in sequence if myList[index] == max_val]
print("Indices of maximum element are:", list_indices)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Indices of maximum element are: [7, 9]
使用 Max()和 enumerate()函数查找多次出现的最大值的索引
enumerate()函数用于给容器对象的元素分配一个计数器。它接受一个类似 list 的容器对象,并返回一个元组列表。在元组列表中,每个元组包含一个数字,该数字将元素的索引表示为其第一个元素,并将列表中的相应值表示为其第二个输入参数。您可以在下面的示例中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
enumerated_list = list(enumerate(myList))
print("Enumerated list is:", enumerated_list)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Enumerated list is: [(0, 1), (1, 2), (2, 23), (3, 32), (4, 12), (5, 44), (6, 34), (7, 55), (8, 46), (9, 55), (10, 21), (11, 12)]
为了使用enumerate()函数找到 max 元素的索引,我们将使用以下步骤。
- 首先,我们将使用
max()函数找到输入列表中的最大元素。 - 然后,我们将创建一个名为
max_indices的空列表来存储列表中 max 元素的索引。 - 创建列表后,我们将使用
enumerate()函数获得元组的枚举列表。 - 一旦我们得到了枚举列表,我们将使用 for 循环遍历元组。
- 迭代时,我们将检查元组中的当前值是否等于最大值。如果是,我们将把与元组中的元素相关联的索引存储在
max_indices中。为此,我们将调用max_indices上的append()方法,将当前索引作为其输入参数。 - 如果元组中的当前值不等于最大值,我们将移动到下一个元组。
在执行 for 循环后,我们将获得max_indices列表中 max 元素的所有索引。您可以在下面的代码中观察到这一点。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
enumerated_list = list(enumerate(myList))
max_indices = []
max_element = max(myList)
for element_tuple in enumerated_list:
index = element_tuple[0]
element = element_tuple[1]
if element == max_element:
max_indices.append(index)
print("Indices of maximum element are:", max_indices)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Indices of maximum element are: [7, 9]
除了在上面的例子中使用 for 循环,您可以使用 list comprehension 和enumerate()函数来查找列表中最大元素的索引,如下所示。
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
enumerated_list = list(enumerate(myList))
max_element = max(myList)
max_indices = [index for (index, element) in enumerated_list if element == max_element]
print("Indices of maximum element are:", max_indices)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Indices of maximum element are: [7, 9]
使用 Numpy 模块在 Python 中查找列表中最大值的索引
我们还可以使用 numpy 模块在 python 中查找列表中最大值的索引。numpy 模块为我们提供了argmax()方法来查找列表中最大值的索引。当在 numpy 数组上调用时,argmax()方法返回最大元素的索引。
为了在 python 中找到列表中的最大值,我们将首先使用array()构造函数将输入列表转换成一个 numpy 数组。array()构造函数将一个类似 list 的容器对象作为它的输入参数。执行后,它返回一个 numpy 数组,包含与输入容器对象中相同数量的元素。
从输入列表创建 numpy 数组后,我们将使用argmax() 函数来查找列表中最大值的索引,如下所示。
import numpy
myList = [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
print("The list is:", myList)
array = numpy.array(myList)
max_index = array.argmax()
print("Index of maximum element is:", max_index)
输出:
The list is: [1, 2, 23, 32, 12, 44, 34, 55, 46, 55, 21, 12]
Index of maximum element is: 7
如果最大值出现多次,argmax()方法将从列表左侧返回第一次出现的最大值的索引。你可以在上面的例子中观察到这一点。
结论
在本文中,我们讨论了在 python 中查找列表中最大值的索引的不同方法。如果只需要找到最大值第一次出现的索引,可以使用带有max() 函数和index()方法的方法。如果您需要获得最大值出现的所有指标,您应该使用使用max()函数和enumerate()函数的方法。
我希望你喜欢阅读这篇文章。要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中删除列表中所有出现的字符的文章。您可能也喜欢这篇关于如何检查 python 字符串是否包含数字的文章。
请继续关注更多内容丰富的文章。
快乐学习!
找到二叉树的镜像
原文:https://www.pythonforbeginners.com/data-structures/find-the-mirror-image-of-a-binary-tree
与 Python 字典、列表或集合不同,二叉树的元素以分层的方式表示。二叉树中的层次结构允许人们找到它的镜像,因为二叉树中的每个元素都有固定的位置。在本文中,我们将研究寻找二叉树镜像的算法。我们还将用 Python 实现该算法,并将在一个示例二叉树上执行它。
二叉树的镜像是什么?
二叉树的镜像是可以通过在树的每个节点交换左子和右子来创建的另一个二叉树。因此,要找到二叉树的镜像,我们只需交换二叉树中每个节点的左子节点和右子节点。让我们试着找出下面这棵树的镜像。

a binary tree
为了找到上述树的镜像,我们将从根开始并交换每个节点的子节点。
在根,我们将交换二叉树的左右子树。这样,20、11 和 22 将进入二叉树的右边子树,53、52 和 78 将进入二叉树的左边,如下所示。

然后我们就进入下一关,交换 53 的孩子。在这里,78 将成为 53 的左孩子,而 52 将成为 53 的右孩子。同样,我们将交换 20 的左孩子和右孩子。这样,22 将成为 20 的左孩子,而 11 将成为 20 的右孩子。在这一级交换节点后的输出二叉树将如下所示。

现在我们将进入下一个阶段。在这个级别,所有节点都是叶节点,没有子节点。因此,在这一级不会有交换,上面的图像是最终的输出。
寻找二叉树镜像的算法
正如我们在上面看到的,我们可以通过交换每个节点的左子节点和右子节点来找到二叉树的镜像。让我们试着用一种系统的方式来表述这个算法。
在最后一个例子中,在第二层,每个节点只有叶节点作为它们的子节点。为了找到这一层节点的镜像,我们交换了这一层每个节点的左右子节点。在根节点,我们交换了它的两个子树。当我们交换每个子树时(叶节点也是子树),我们可以使用递归实现这个算法。
寻找二叉树的镜像的算法可以用公式表示如下。
- 从根节点开始。
- 递归查找左侧子树的镜像。
- 递归查找右边子树的镜像。
- 交换左右子树。
Python 中算法的实现
现在我们将实现算法,用 Python 找到二叉树的镜像。
from queue import Queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def mirror(node):
if node is None:
return None
mirror(node.leftChild)
mirror(node.rightChild)
temp = node.leftChild
node.leftChild = node.rightChild
node.rightChild = temp
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# 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:
inorder(root.leftChild)
print(root.data, end=" ")
inorder(root.rightChild)
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
print("Inorder Traversal of tree before mirroring:")
inorder(root)
mirror(root)
print("\nInorder Traversal of tree after mirroring:")
inorder(root)
输出:
Inorder Traversal of tree before mirroring:
11 20 22 50 52 53 78
Inorder Traversal of tree after mirroring:
78 53 52 50 22 20 11
这里,我们创建了一个二叉树节点。之后,我们定义了向二叉树插入元素的函数。我们还使用有序树遍历算法在找到镜像之前和之后打印树的元素。
结论
在这篇文章中,我们实现了一个算法来寻找一个二叉树的镜像。要了解更多关于其他数据结构的知识,可以阅读这篇关于 Python 中的链表的文章。请继续关注更多关于用 Python 实现不同算法的文章。
用 Python 求一个整数的位数之和
原文:https://www.pythonforbeginners.com/basics/find-the-sum-of-digits-of-an-integer-in-python
当你写程序的时候,整数几乎无处不在。在本文中,我们将讨论在 python 中寻找给定整数的数字总和的方法。
如何求一个整数的位数之和?
求一个数 N 的位数之和,我们可以提取一个数的位数,然后一个一个的相加。为此,我们将从右到左提取数字。为了提取数字,我们将数字除以 10,并在每次除法运算中存储余数。我们将继续用 10 除这个数,直到它变成 0。这样我们就可以一个一个的提取数字了。
例如,如果给我们一个数字 12345,我们将如下计算数字的和。
- 首先,我们将把变量 sumOfDigits 初始化为零。
- 之后,我们将 12345 除以 10。
- 除法之后,我们将在 sumOfDigits 中添加 reminder 5,并将数字更新为 1234。
- 然后,我们将 1234 除以 10。
- 除法之后,我们将在 sumOfDigits 中添加 reminder 4,并将数字更新为 123。
- 同样,我们将 123 除以 10。
- 除法之后,我们将在 sumOfDigits 中添加 reminder 3,并将数字更新为 12。
- 同样,我们将 12 除以 10。
- 除法之后,我们将在 sumOfDigits 中添加 reminder 2,并将数字更新为 1。
- 现在,我们将 1 除以 10。
- 除法之后,我们会将 reminder 1 加到 sumOfDigits 上,并将数字更新为 0。
- 当数字变为 0 时,我们将在变量 sum of digits 中得到数字 12345 的数字总和,即 15。
用 Python 实现
正如我们在上面看到的,要在 python 中找到一个整数的位数之和,我们只需要将这个数除以 10,直到它变成 0。与此同时,我们必须将每个除法中的余数相加,以获得位数之和。我们可以如下实现程序来执行这个操作。
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
input_number = 12345
output = calculate_sum_of_digits(input_number)
print("Sum of digits of {} is {}.".format(input_number, output))
input_number = 126
output = calculate_sum_of_digits(input_number)
print("Sum of digits of {} is {}.".format(input_number, output))
输出:
Sum of digits of 12345 is 15.
Sum of digits of 126 is 9.
结论
在本文中,我们讨论并实现了一个用 Python 计算整数位数总和的程序。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。你可能也会喜欢这篇关于 python 中的复数的文章。
Python For 循环、While 循环和嵌套循环
原文:https://www.pythonforbeginners.com/loops/for-while-and-nested-loops-in-python
所有的编程语言都需要多次做类似的事情,这叫做迭代。
Python 中迭代的例子是循环。Python 使用 For 循环、While 循环和嵌套循环。
对于循环
Python 中的 For 循环允许我们迭代一个序列的元素,当你有一段想要重复 n 次的代码时,经常使用它。
for 循环语法如下:
for x in list :
do this..
do this..
for 循环的示例
假设您有一个如下所示的浏览器列表。对于我们赋予变量 browser 的每个元素,在浏览器列表中,打印出变量 browser
browsers = ["Safari", "Firefox", "Chrome"]
for browser in browsers:
print browser
for 循环的另一个例子
为了获得更多关于 for 循环的实践,请参见以下示例:
numbers = [1,10,20,30,40,50]
sum = 0
for number in numbers:
sum = sum + number
print sum
循环单词
这里我们使用 for 循环来遍历单词 computer
word = "computer"
for letter in word:
print letter
使用 python 范围函数
Python 编程语言有一个内置函数“range ”,可以生成一个包含我们在范围内指定的数字的列表。
给定的端点决不是生成列表的一部分;
range(10)生成 10 个值的列表,长度为 10 的序列的合法索引。
可以让范围函数从另一个数字开始,或者指定一个不同的增量(甚至是负数)。
这被称为“步骤”。
范围函数语法
范围(开始、停止、步进
开始是你开始的位置。
Stop 是停止的数字,不包括。
步长是增量,默认值为 1。
范围函数示例
例 1
打印从 0 开始到 5 结束的数字(不包括 5)。此示例使用了一个带有范围的 for 循环。
>>> for number in range(0,5): print number
...
0
1
2
3
4
>>>
例 2
打印从 1 开始到 10 结束的范围,不包括。这个范围示例没有使用 for 循环。
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
例 3
这个 range 函数示例被分配给一个变量。然后使用 for 循环迭代该变量。
>>> a = range(1,10)
>>> for i in a: print i
...
1
2
3
4
5
6
7
8
9
>>>
例 4
这是一个使用范围内步长的示例。步长默认值为 1。在这个例子中,我们使用-2 作为步长,从 21 开始,直到-1。
>>> for a in range(21,-1,-2): print a
...
21
19
17
15
13
11
9
7
5
3
1
>>>
While 循环
Python 中的 while 循环告诉计算机只要满足条件就做某件事,它的构造由一段代码和一个条件组成。
在 while 和冒号之间,有一个值首先为真,但随后为假。
计算条件,如果条件为真,则执行块中的代码。
只要该语句为真,其余的代码就会运行。
将要运行的代码必须在缩进的块中。
它是这样工作的:“虽然这是真的,但这样做”
While 循环的示例
下面的例子是这样的:只要变量 I 的值小于列表的长度(浏览器),就打印出变量名。
循环语法:
browsers = ["Safari", "Firefox", "Google Chrome"]
i = 0
while i < len(browsers):
print browsers[i]
i = i + 1
While 循环的另一个例子
下面的脚本首先将变量 counter 设置为 0。
每当 while 循环运行一次,计数器的值就增加 2。只要变量计数器小于或等于 100,循环就会运行。
counter = 0
while counter <= 100:
print counter
counter = counter + 2
使用 While 循环计数
这个小脚本会从 0 数到 9。i = i + 1 每运行一次,I 值就加 1。
i = 0
while i < 10:
print i
i = i + 1
永恒的循环
注意不要在 Python 中形成一个永恒的循环,当你按下 Ctrl+C 时,循环会继续,确保你的 while 条件会在某个时候返回 false。
这个循环意味着 while 条件将永远为真,并将永远打印 Hello World。
while True:
print "Hello World"
嵌套循环
在一些脚本中,你可能想要使用嵌套循环。
Python 中的嵌套循环是循环中的循环。
当你有一段你想运行 x 次的代码,然后在这段代码中你想运行 y 次的代码
在 Python 中,每当有人有一个列表的列表时——一个可迭代对象中的一个可迭代对象——就会大量使用这些。
for x in range(1, 11):
for y in range(1, 11):
print '%d * %d = %d' % (x, y, x*y)
打破循环
要从循环中脱离,可以使用关键字“break”。Break 停止循环的执行,与测试无关。break 语句可以在 while 和 for 循环中使用。
中断示例
这将要求用户输入。当用户键入“停止”时,循环结束。
while True:
reply = raw_input('Enter text, [type "stop" to quit]: ')
print reply.lower()
if reply == 'stop':
break
另一个破裂的例子
让我们再看一个如何使用 break 语句的例子。
while True:
num=raw_input("enter number:")
print num
if num=='20':
break
让我们举例说明如何在 for 循环中使用 break 语句。
for i in range(1,10):
if i == 3:
break
print i
继续
continue 语句用于告诉 Python 跳过当前循环块中的其余语句,并继续循环的下一次迭代。
continue 语句拒绝当前循环迭代中的所有剩余语句,并将控制移回循环顶部。
continue 语句可以在 while 和 for 循环中使用。
for i in range(1,10):
if i == 3:
continue
print i
继续示例
这个例子取自tutorialspoint.com
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
输出
上述输出将产生以下结果:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Good bye!
及格
pass 语句什么也不做。当语法上需要一个语句,但程序不需要动作时,可以使用它。
>>> while True:
... pass # Busy-wait for keyboard interrupt
...
Python 中的分数模块
原文:https://www.pythonforbeginners.com/basics/fractions-module-in-python
你一定在 python 中使用过整数和浮点数这样的数字数据类型。但是你用过分数的实际形式吗?在本文中,我们将学习分数,并使用 python 中的分数模块对分数进行运算。
如何使用 Python 中的分数模块?
我们可以使用 python 中分数模块的分数方法来创建分数形式的有理数。我们可以像下面这样导入模块。
import fractions
在 python 中,我们可以将整数、浮点数或字符串转换成分数。为了将两个整数的比率转换为分数,我们使用了分数模块的 fraction()方法,并将分子作为第一个参数传递,将分母作为第二个参数传递。该函数返回一个分数对象,如下所示。
import fractions
myInt1=1
myInt2=2
print("Integer 1(numerator) is:",myInt1)
print("Integer 2(denominator) is:",myInt2)
myFraction=fractions.Fraction(myInt1,myInt2)
print("Fraction value is:",myFraction)
输出:
Integer 1(numerator) is: 1
Integer 2(denominator) is: 2
Fraction value is: 1/2
我们可以使用 fractions 模块的 fraction 方法从浮点数中获得一个分数值。当我们将一个浮点数作为输入传递给 Fraction()方法时,它返回相应的分数值,如下所示。
import fractions
myFloat=0.5
print("Floating point number is:",myFloat)
myFraction=fractions.Fraction(myFloat)
print("Fraction value is:",myFraction)
输出:
Floating point number is: 0.5
Fraction value is: 1/2
我们也可以使用 fraction()方法将字符串转换成分数。我们可以将分数的字符串表示或字符串中的浮点文字作为输入传递给 fraction 方法,该方法返回相应的分数值,如下所示。
import fractions
myStr1="0.5"
print("String literal is:",myStr1)
myFraction1=fractions.Fraction(myStr1)
print("Fraction value is:",myFraction1)
myStr2="1/2"
print("String literal is:",myStr2)
myFraction2=fractions.Fraction(myStr2)
print("Fraction value is:",myFraction2)
输出:
String literal is: 0.5
Fraction value is: 1/2
String literal is: 1/2
Fraction value is: 1/2
分数怎么四舍五入?
我们可以在 python 中使用 round()方法,根据分数分母所需的位数,对分数进行四舍五入。round()方法把要舍入的分数作为第一个参数,把分母要舍入到的位数作为第二个参数。该函数返回分母中有所需位数的分数。这可以这样理解。
import fractions
myInt1=50
myInt2=3
myFraction=fractions.Fraction(myInt1,myInt2)
print("Fraction value is:",myFraction)
rounded=round(myFraction,2)
print("Rounded value is:",rounded)
输出:
Fraction value is: 50/3
Rounded value is: 1667/100
当我们没有将分母四舍五入的位数作为第二个参数传递时,round()方法会将分数转换为最接近的整数。这可以看如下。
import fractions
myInt1=50
myInt2=3
myFraction=fractions.Fraction(myInt1,myInt2)
print("Fraction value is:",myFraction)
rounded=round(myFraction)
print("Rounded value is:",rounded)
输出:
Fraction value is: 50/3
Rounded value is: 17
从分数中获取分子和分母
我们也可以从分数中提取分子和分母。为了提取分子,我们使用 fraction 对象的“分子”字段。类似地,为了提取分母,我们使用 fraction 对象的“分母”字段。这可以从下面的例子中理解。
import fractions
myInt1=50
myInt2=3
myFraction=fractions.Fraction(myInt1,myInt2)
print("Fraction value is:",myFraction)
print("Numerator is:",myFraction.numerator)
print("Denominator is:",myFraction.denominator)
输出:
Fraction value is: 50/3
Numerator is: 50
Denominator is: 3
分数的算术运算
我们可以使用 python 中的分数模块对分数执行加减乘除等算术运算,就像我们对整数和浮点数等其他数字数据类型执行这些运算一样。
我们可以在 python 中对两个给定的分数执行算术运算,如下所示。
import fractions
myFraction1=fractions.Fraction(50,3)
myFraction2=fractions.Fraction(1,2)
print("First Fraction value is:",myFraction1)
print("Second Fraction value is:",myFraction2)
print("Fraction1 + Fraction2 is:",myFraction1 + myFraction2)
print("Fraction1 - Fraction2 is:",myFraction1 - myFraction2)
print("Fraction1 * Fraction2 is:",myFraction1 * myFraction2)
print("Fraction1 / Fraction2 is:",myFraction1 / myFraction2)
输出:
First Fraction value is: 50/3
Second Fraction value is: 1/2
Fraction1 + Fraction2 is: 103/6
Fraction1 - Fraction2 is: 97/6
Fraction1 * Fraction2 is: 25/3
Fraction1 / Fraction2 is: 100/3
使用分数模块从浮点数中获取近似有理值
我们可以从任何浮点或十进制值中获得分数形式的有理数。为了从十进制数中获得分数,我们可以将十进制数传递给 fraction()方法,该方法会将它们转换为有理数,如下所示。
import fractions
myFloat= 22/7
print("Floating point value is:",myFloat)
myFraction=fractions.Fraction(myFloat)
print("Fraction value is:",myFraction)
输出:
Floating point value is: 3.142857142857143
Fraction value is: 7077085128725065/2251799813685248
在获得上述格式的分数后,我们可以使用 limit_denominator()方法限制分母的最高值。当对分数调用 limit_denominator()方法时,该方法将分母的最大允许值作为输入,并返回相应的分数。这可以从下面的例子中理解。
import fractions
myFloat= 22/7
print("Floating point value is:",myFloat)
myFraction=fractions.Fraction(myFloat)
print("Fraction value is:",myFraction)
myFraction1=myFraction.limit_denominator(100)
print("Approximate Fraction value with denominator limited to 100 is:",myFraction1)
输出:
Floating point value is: 3.142857142857143
Fraction value is: 7077085128725065/2251799813685248
Approximate Fraction value with denominator limited to 100 is: 22/7
结论
在本文中,我们研究了分数数据类型,并使用 python 中的分数模块实现了它。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
Python 中的 Frozenset
原文:https://www.pythonforbeginners.com/basics/frozenset-in-python
使用 python 编程时,您可能在程序中使用过集合、列表和字典。在本文中,我们将研究 Python 中另一个名为 frozenset 的容器对象。我们将讨论如何创建一个 frozenset,以及如何访问它的元素。
Python 中的 frozenset 是什么?
您可能使用过 python 中的集合。Frozensets 是具有集合的所有属性但不可变的容器对象。frozenset 与集合的关系类似于元组与列表的关系。冷冻集的主要特性如下。
- 冷冻集包含独特的元素。
- 它们是不可变的,不能在 frozenset 中添加、修改或删除任何元素。
- 我们只能在创建 frozenset 对象的过程中向 frozenset 添加元素。
现在让我们讨论如何创建一个冷冻集并访问它的元素。
如何用 Python 创建一个 frozenset?
我们可以使用 frozenset()构造函数创建一个 frozenset。frozenset()构造函数接受一个容器对象作为输入,并用容器对象的元素创建一个 frozenset。例如,我们可以创建一个包含列表元素的 frozenset,如下所示。
myList = [1, 2, 3, 4, 5]
print("The given list is:")
print(myList)
myFrozenset = frozenset(myList)
print("The output frozenset is:")
print(myFrozenset)
输出:
The given list is:
[1, 2, 3, 4, 5]
The output frozenset is:
frozenset({1, 2, 3, 4, 5})
类似地,我们可以使用集合的元素创建一个 frozenset,如下所示。
mySet = {1, 2, 3, 4, 5}
print("The given set is:")
print(mySet)
myFrozenset = frozenset(mySet)
print("The output frozenset is:")
print(myFrozenset)
输出:
The given set is:
{1, 2, 3, 4, 5}
The output frozenset is:
frozenset({1, 2, 3, 4, 5})
当没有输入给 frozenset()构造函数时,它创建一个空的 frozenset。
myFrozenset = frozenset()
print("The output frozenset is:")
print(myFrozenset)
输出:
The output frozenset is:
frozenset()
当我们将一个 python 字典作为输入传递给 frozenset()构造函数时,它会创建一个字典键的 frozenset。这可以在下面的例子中观察到。
myDict = {1:1, 2:4, 3:9, 4:16, 5:25}
print("The given dictionary is:")
print(myDict)
myFrozenset = frozenset(myDict)
print("The output frozenset is:")
print(myFrozenset)
输出:
The given dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The output frozenset is:
frozenset({1, 2, 3, 4, 5})
从冷冻集中访问元素
与其他容器对象类似,我们可以使用迭代器访问 frozenset 的元素,如下所示。
mySet = {1, 2, 3, 4, 5}
print("The given set is:")
print(mySet)
myFrozenset = frozenset(mySet)
print("The elements of the frozenset are:")
iterator=iter(myFrozenset)
for i in iterator:
print(i)
输出:
The given set is:
{1, 2, 3, 4, 5}
The elements of the frozenset are:
1
2
3
4
5
我们还可以使用 for 循环遍历 frozenset 的元素,如下所示。
mySet = {1, 2, 3, 4, 5}
print("The given set is:")
print(mySet)
myFrozenset = frozenset(mySet)
print("The elements of the frozenset are:")
for i in myFrozenset:
print(i)
输出:
The given set is:
{1, 2, 3, 4, 5}
The elements of the frozenset are:
1
2
3
4
5
向冷冻集添加元素
我们不能向 frozenset 添加元素,因为它们是不可变的。同样,我们不能修改或删除 frozenset 中的元素。
Python 中 set 和 frozenset 的区别
python 中的 frozenset 可以被认为是不可变的集合。set 和 frozenset 的主要区别在于我们不能修改 frozenset 中的元素。集合和冷冻集的其他性质几乎相同。
结论
在本文中,我们讨论了如何用 python 创建 frozenset,以及它的属性是什么。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 刽子手游戏
原文:https://www.pythonforbeginners.com/code-snippets-source-code/game-hangman
在 Python 中,我们可以非常快速地创建简单的游戏。在本文中,我们将讨论 Python Hangman 游戏的实现。
Hangman 游戏是怎么玩的?
刽子手游戏是一个多人游戏。在这个游戏中,一个玩家选择一个单词。其他玩家有一定次数的猜测来猜测单词中的字符。如果玩家能够在一定的尝试中猜出整个单词中的字符,他们就赢了。否则,他们就输了。
如何用 Python 创建 Hangman 游戏?
为了用 Python 创建一个刽子手游戏,我们将使用以下步骤。
- 首先,我们将询问用户的姓名。我们将使用 input()方法获取用户输入。执行后,input()方法接受用户的输入并返回一个字符串。
- 接下来,我们将选择一个单词,并要求用户开始猜测单词中的字符。
- 我们还将定义用户可以尝试的最大次数。
- 现在,我们将使用一个 while 循环来反复要求用户猜测字符,直到尝试用尽为止。
- 在 while 循环中,如果用户猜出了正确的字符。我们将在回复中包括它。否则,我们将通知用户他们犯了一个错误。
- 如果用户能够在最大尝试次数内猜出单词的所有字符,他们就赢得了游戏。
- 如果用户在猜出整个单词之前用尽了所有的尝试,他们就输了。
刽子手游戏的 Python 代码
以下是经典游戏《刽子手》的一个 Python 脚本。一行破折号代表要猜的单词。如果玩家猜出单词中的一个字母,脚本会将它写在所有正确的位置上。玩家有 10 次机会猜这个单词。你可以很容易地通过改变变量来定制游戏。
确保你理解每一行是做什么的。出于这个原因,所有的 python 语句都已经用 python 注释解释过了。
#importing the time module
import time
#welcoming the user
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
#wait for 1 second
time.sleep(1)
print ("Start guessing...")
time.sleep(0.5)
#here we set the secret. You can select any word to play with.
word = ("secret")
#creates an variable with an empty value
guesses = ''
#determine the number of turns
turns = 10
# Create a while loop
#check if the turns are more than zero
while turns > 0:
# make a counter that starts with zero
failed = 0
# for every character in secret_word
for char in word:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print (char,end=""),
else:
# if not found, print a dash
print ("_",end=""),
# and increase the failed counter with one
failed += 1
# if failed is equal to zero
# print You Won
if failed == 0:
print ("You won")
# exit the script
break
# ask the user go guess a character
guess = input("guess a character:")
# set the players guess to guesses
guesses += guess
# if the guess is not found in the secret word
if guess not in word:
# turns counter decreases with 1 (now 9)
turns -= 1
# print wrong
print ("Wrong")
# how many turns are left
print ("You have", + turns, 'more guesses' )
# if the turns are equal to zero
if turns == 0:
# print "You Lose"
print ("You Lose" )
输出:
What is your name? Aditya
Hello, Aditya Time to play hangman!
Start guessing...
______guess a character:s
s_____guess a character:e
se__e_guess a character:c
sec_e_guess a character:r
secre_guess a character:e
secre_guess a character:t
secretYou won
好好享受吧!!
结论
在本文中,我们讨论了用 Python 实现 hangman 游戏。要了解更多关于 python 编程的知识,你可以阅读这篇关于字符串操作的文章。你可能也会喜欢这篇关于 python 的文章,如果你是简写的话。
Python 游戏:掷色子
原文:https://www.pythonforbeginners.com/code-snippets-source-code/game-rolling-the-dice
又到了写游戏脚本的时候了。
它是如何工作的
这是一个经典的“掷骰子”程序。
为此,我们将使用 random 模块,因为我们想随机化从骰子中得到的数字。
我们设置了两个变量(最小和最大),骰子的最低和最高数量。
然后我们使用 while 循环,这样用户可以再次掷骰子。
roll_again 可以设置为任何值,但这里设置为“yes”或“y”,
但您也可以添加其他变量。
掷色子
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print "Rolling the dices..."
print "The values are...."
print random.randint(min, max)
print random.randint(min, max)
roll_again = raw_input("Roll the dices again?")
Python 中的生成器理解
原文:https://www.pythonforbeginners.com/basics/generator-comprehension-in-python
您可能已经使用列表理解从不同的序列和容器对象创建列表。在本文中,我们将讨论如何理解用 Python 创建生成器。我们还将讨论生成器理解的例子,以及如何用它来代替列表理解。
什么是生成器理解?
生成器理解是初始化生成器以访问容器对象或数据序列中的元素的一种方式。
通常,我们通过使用 yield 语句实现一个生成器函数来创建一个生成器对象。例如,假设您想要创建一个生成器,它给出给定列表中元素的平方作为输出。我们可以使用 yield 语句创建这样一个生成器,如下所示。
def num_generator():
for i in range(1, 11):
yield i
gen = num_generator()
print("Values obtained from generator function are:")
for element in gen:
print(element)
输出:
Values obtained from generator function are:
1
2
3
4
5
6
7
8
9
10
我们可以使用 generator comprehension 从单个语句中的任何序列创建一个生成器,而不是实现 generator 函数来创建一个生成器。因此,让我们讨论生成器理解的语法和实现。
生成器理解语法
生成器理解的语法几乎与列表理解相同。
集合理解的语法是:生成器 = ( 表达式 for 元素initerableif条件 )
- 可迭代 可以是任何可迭代对象,如列表、集合、元组或字典,我们必须从这些对象创建一个新的生成器来访问其元素。
- 元素 是我们正在为其创建生成器的可迭代对象的元素。
- 表达式 包含从 元素 中导出的值或任何数学表达式。
- 条件 是在生成器中排除或包含一个 元素 所需的条件表达式。条件语句是可选的,如果必须访问 iterable 的所有元素,可以省略“if condition”。
- 生成器 是 Python 中使用 generator comprehension 新创建的生成器的名称。
让我们使用一个简单的程序来理解这个语法,使用 generator comprehension 从现有的列表中创建生成器。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:",myList)
mygen = (element**2 for element in myList)
print("Elements obtained from the generator are:")
for ele in mygen:
print(ele)
输出:
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:",myList)
mygen = (element**2 for element in myList)
print("Elements obtained from the generator are:")
for ele in mygen:
print(ele)
在上面的程序中,我们得到了一个由 10 个数字组成的列表,我们创建了一个生成器,它给出给定列表元素的平方作为输出。在语句mygen =(myList 中的元素 * 2)*中,生成器 comprehension 已经被用来创建名为 mygen 的 生成器,它给出 myList 中元素的平方作为输出。
让我们看一个使用条件语句的生成器理解的例子。假设您想要创建一个生成器,它只输出列表中偶数的平方。这可以使用生成器理解来实现,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
mygen = (element ** 2 for element in myList if element % 2 == 0)
print("Elements obtained from the generator are:")
for ele in mygen:
print(ele)
输出:
The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the generator are:
4
16
36
64
100
在上面的程序中,我们得到了一个由 10 个数字组成的列表,我们创建了一个生成器,它给出给定集合中偶数元素的平方作为输出。在语句 mygen =(如果元素% 2 == 0,则 myList 中的元素为元素 * 2)*中,generator comprehension 用于创建生成器 mygen ,该生成器给出 myList 中那些偶数元素的平方作为输出。
发电机理解的好处
在 Python 中使用生成器理解而不是生成器函数来创建生成器给了我们很多好处。
- 生成器理解使我们能够使用更少的代码行实现相同的功能。
- 与列表理解或集合理解不同,生成器理解不初始化任何对象。因此,您可以使用生成器理解而不是列表理解或集合理解来减少程序的内存需求。
- 生成器理解也使代码更具可读性,这有助于源代码的调试和维护。
结论
在本文中,我们讨论了 Python 中的生成器理解。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的生成器
原文:https://www.pythonforbeginners.com/basics/generators-in-python
你了解 python 中的函数吗?如果您的回答是肯定的,那么让我带您了解一下 python 中生成器函数和生成器的有趣概念。在这篇文章中,我们将看看如何在程序中定义和使用生成器。我们还会用一些例子来看看生成器和函数有什么不同。
什么是函数?
在 python 中,函数是完成某些特定工作的代码块。例如,一个函数可以将两个数相加,一个函数可以从你的计算机中删除一个文件,一个函数可以做任何你想让它做的特定任务。
函数也使用 return 语句返回所需的输出值。下面给出了一个函数的例子。它将两个数字作为输入,将它们相乘,并使用 return 语句返回输出值。
def multiplication(num1, num2):
product = num1 * num2
return product
result = multiplication(10, 15)
print("Product of 10 and 15 is:", result)
输出:
Product of 10 and 15 is: 150
什么是生成器函数?
生成器函数类似于 python 中的函数,但它向调用者提供类似迭代器的生成器作为输出,而不是对象或值。此外,我们在生成器函数中使用 yield 语句而不是 return 语句。yield 语句在生成器函数执行时暂停它的执行,并将输出值返回给调用者。生成器函数可以有一个或多个 yield 语句,但不能有 return 语句。
我们可以用类似于 python 中函数的方式定义一个生成器函数,但是我们不能使用 return 语句。相反,我们使用收益表。下面是一个生成器函数的示例,它将从 1 到 10 的数字返回给调用者。
def num_generator():
for i in range(1, 11):
yield i
gen = num_generator()
print("Values obtained from generator function are:")
for element in gen:
print(element)
输出:
Values obtained from generator function are:
1
2
3
4
5
6
7
8
9
10
Python 中的生成器是什么?
python 中的生成器是一种迭代器,用于使用 next()函数执行生成器函数。为了执行一个生成器函数,我们将它赋给生成器变量。然后我们使用 next()方法来执行生成器函数。
next()函数将生成器作为输入,并执行生成器函数,直到下一个 yield 语句。之后,暂停执行生成器功能。为了继续执行,我们再次调用 next()函数,将生成器作为输入。同样,生成器函数执行到下一个 yield 语句。这个过程可以继续,直到生成器函数的执行完成。从下面的例子可以理解这个过程。
def num_generator():
yield 1
yield 2
yield 3
yield 4
gen = num_generator()
for i in range(4):
print("Accessing element from generator.")
element = next(gen)
print(element)
输出:
Accessing element from generator.
1
Accessing element from generator.
2
Accessing element from generator.
3
Accessing element from generator.
4
Process finished with exit code 0
在上面的输出中,您可以看到每次调用 next()函数时,都会打印下一个 yield 语句中的元素。它显示了每次调用 next()函数时,生成器函数都会继续执行。
如果在生成器函数完成执行后,我们试图用生成器作为输入调用 next()函数,next()函数将引发 StopIteration 异常。因此,建议在除了块之外的 python try 中使用 next()函数。此外,我们还可以使用 for 循环遍历 python 中的生成器。它将产生与使用 next()函数执行程序时相同的结果。
def num_generator():
yield 1
yield 2
yield 3
yield 4
gen = num_generator()
for i in gen:
print("Accessing element from generator.")
print(i)
输出:
Accessing element from generator.
1
Accessing element from generator.
2
Accessing element from generator.
3
Accessing element from generator.
4
Process finished with exit code 0
Python 中的生成器示例
因为我们已经讨论了 Python 中的生成器和生成器函数,所以让我们实现一个程序来更好地理解上面的概念。在下面的程序中,我们实现了一个生成器函数,它将一个列表作为输入,并计算列表中元素的平方。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def square_generator(input_list):
for element in input_list:
print("Returning the square of next element:",element)
yield element*element
print("The input list is:",myList)
gen = square_generator(myList)
for i in range(10):
print("Accessing square of next element from generator.")
square = next(gen)
print(square)
输出:
The input list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Accessing square of next element from generator.
Returning the square of next element: 1
1
Accessing square of next element from generator.
Returning the square of next element: 2
4
Accessing square of next element from generator.
Returning the square of next element: 3
9
Accessing square of next element from generator.
Returning the square of next element: 4
16
Accessing square of next element from generator.
Returning the square of next element: 5
25
Accessing square of next element from generator.
Returning the square of next element: 6
36
Accessing square of next element from generator.
Returning the square of next element: 7
49
Accessing square of next element from generator.
Returning the square of next element: 8
64
Accessing square of next element from generator.
Returning the square of next element: 9
81
Accessing square of next element from generator.
Returning the square of next element: 10
100
在上面的例子中,您可以看到,每当使用生成器作为输入执行 next()函数时,它都会执行一次循环,直到 yield 语句。一旦 yield 语句被执行,生成器函数的执行就会暂停,直到我们再次执行 next()函数。
函数和生成器函数的主要区别
函数和生成器函数的主要区别如下。
- 函数有一个 return 语句,而生成器函数有一个 yield 语句。
- 函数在执行第一条 return 语句后停止执行。然而,生成器函数只是在 yield 语句执行后暂停执行。
- 函数返回一个值或一个容器对象,而生成器函数返回一个生成器对象。
结论
在本文中,我们讨论了 Python 中的生成器函数和生成器。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
从字典中的值获取键
原文:https://www.pythonforbeginners.com/dictionary/get-key-from-value-in-dictionary
在 python 中,我们可以通过简单地使用语法 dict_name[key_name]来使用键获取字典中的值。但是当我们有值时,没有任何方法可以提取与值相关的键。在这篇文章中,我们将看到在字典中从给定值中获取密钥的方法。
通过在字典中搜索项目从值中获取键
这是获取值的键的最简单的方法。在这个方法中,我们将检查每个键-值对,以找到与当前值相关联的键。对于这个任务,我们将为一个 python 字典使用 items()方法。items()方法返回包含键值对的元组列表。我们将搜索每个元组,以找到与我们的值相关联的键,如下所示。
myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Dictionary is:")
print(myDict)
dict_items=myDict.items()
print("Given value is:")
myValue="PFB"
print(myValue)
print("Associated Key is:")
for key,value in dict_items:
if value==myValue:
print(key)
输出:
Dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
Given value is:
PFB
Associated Key is:
acronym
在上面的程序中,我们使用 myDict.items()在 myDict 中创建了一个条目列表,然后我们检查列表中的每个条目,以找到我们的值的键。
使用 python 列表从值中获取键
我们可以创建一个单独的键和值的列表,然后使用 index()方法从给定的值中检索键。对于此任务,我们将首先使用 keys()方法创建字典中的键列表,然后使用 values()方法创建字典中的值列表。现在我们将使用 index()方法从值列表中获取给定值的索引。因为我们知道关键字列表与值列表中的值具有相同的关键字顺序,所以值列表中的值的索引将与关键字列表中的关联关键字的索引相同。因此,在值列表中找到值的索引后,我们可以在相同索引的键列表中找到键。这可以如下进行。
myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Dictionary is:")
print(myDict)
dict_keys=list(myDict.keys())
dict_values=list(myDict.values())
print("Given value is:")
myValue="PFB"
print(myValue)
val_index=dict_values.index(myValue)
print("Associated key is:")
myKey=dict_keys[val_index]
print(myKey)
输出:
Dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
Given value is:
PFB
Associated key is:
acronym
使用列表理解从值中获取键
不使用 index()方法,我们可以使用 list comprehension 来获取与给定值相关联的键。为了找到这个键,我们将使用如下的列表理解来创建一个键的列表,这些键的关联值等于给定值。
myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Dictionary is:")
print(myDict)
dict_items=myDict.items()
print("Given value is:")
myValue="PFB"
print(myValue)
print("Associated key is:")
myKey=[key for key,value in dict_items if value==myValue]
print(myKey)
输出:
Dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
Given value is:
PFB
Associated key is:
['acronym']
结论
在本文中,我们看到了使用 list comprehension、items()方法和 list index()方法从 python 字典中获取键的三种方法。请继续关注更多内容丰富的文章。
获取 Python 中列表的最后一个元素
原文:https://www.pythonforbeginners.com/basics/get-the-last-element-of-a-list-in-python
列表是 python 程序中最常用的数据结构之一。在本文中,我们将研究用 python 获取列表最后一个元素的不同方法。为此,我们将使用索引、pop()方法、切片和反向迭代器等方法。
使用 Python 中的索引获取列表的最后一个元素
python 中的索引是一种从列表中访问元素的方式。在 python 中,我们可以使用正索引,也可以使用负索引。正索引从零开始,对应于列表的第一个元素,列表的最后一个元素由索引“listLen-1”标识,其中“listLen”是列表的长度。
或者,负索引从-1 开始,对应于列表的最后一个元素。一直到"-listLen ",其中 listLen 是列表的长度。索引“-listLen”对应于列表中的第一个元素。
要获得一个列表的最后一个元素,我们可以首先使用 len()函数找到列表的长度。然后,我们可以访问索引“listLen-1”处的列表的最后一个元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
listLen = len(myList)
lastElement = myList[listLen - 1]
print("Last element of the list is:", lastElement)
输出:
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
或者,我们可以使用负索引来访问列表的最后一个元素。列表的最后一个元素在索引-1 处,可以如下访问。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = myList[- 1]
print("Last element of the list is:", lastElement)
输出:
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
我们可以看到,在使用负索引时,我们不必计算列表的长度。
使用 pop()方法
pop()方法用于从指定的索引中移除列表中的任何元素。它将元素的索引作为可选的输入参数,并在从列表中删除元素后,返回指定索引处的元素。如果没有传递输入参数,它将在删除后返回列表的最后一个元素。
我们可以使用 pop()方法获取列表的最后一个元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = myList.pop()
print("Last element of the list is:", lastElement)
输出:
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
请记住,pop()方法还会删除被访问的元素。所以,只有当你还想删除列表的最后一个元素时,才使用这个方法。
使用 Python 中的切片获取列表的最后一个元素
在 python 中,切片是创建字符串或列表的一部分的操作。通过切片,我们可以访问任何字符串、元组或列表的不同部分。为了对名为的列表执行切片,我们使用语法 listName[start,end,interval],其中“start”和“end”分别是切片列表在原始列表中开始和结束的索引。“间隔”用于选择序列中的元素。从列表中的索引处选择元素,这些索引距离起始索引是“间隔”的整数倍。
为了使用 python 中的切片来访问列表的最后一个元素,我们可以以这样的方式对列表进行切片,使得它只包含最后一个元素。然后我们可以如下访问该元素。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = myList[-1:][0]
print("Last element of the list is:", lastElement)
输出:
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
使用反向迭代器获取列表的最后一个元素
我们可以使用反向迭代器来获取列表的最后一个元素。要创建反向迭代器,我们可以使用 reversed()方法。reversed()方法接受任何 iterable 对象作为输入,并返回 iterable 的反向迭代器。
为了获得列表的最后一个元素,我们将首先使用 reversed()方法创建列表的反向迭代器。然后我们将访问反向迭代器的第一个元素,这将是原始列表的最后一个元素。这可以如下进行。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
reverseIter = reversed(myList)
lastElement = next(reverseIter)
print("Last element of the list is:", lastElement)
输出:
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
使用 itemgetter 获取列表的最后一个元素
我们可以创建一个 itemgetter 对象来访问列表的最后一个元素。itemgetter()方法是在 python 的运算符模块中定义的。itemgetter()方法将索引作为输入,创建一个可调用的对象。callable 对象将 iterable 作为输入,并提取指定索引处的元素。
要访问列表的最后一个元素,我们可以调用 itemgetter()方法,输入索引为-1,然后我们可以访问列表的最后一个元素,如下所示。
import operator
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = operator.itemgetter(-1)(myList)
print("Last element of the list is:", lastElement)
输出:
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
结论
在本文中,我们看到了在 python 中获取列表最后一个元素的不同方法。要阅读更多关于列表的内容,请阅读这篇关于 python 中的列表理解的文章。请继续关注更多内容丰富的文章。
从 Apache 日志中获取热门页面
Apache 日志文件可能非常大,很难阅读。这里有一种从 Apache 日志文件中获取最常访问的页面(或文件)列表的方法。
在这个例子中,我们只想知道 GET 请求的 URL。我们将使用 Python 集合中的奇妙计数器
import collections
logfile = open("yourlogfile.log", "r")
clean_log=[]
for line in logfile:
try:
# copy the URLS to an empty list.
# We get the part between GET and HTTP
clean_log.append(line[line.index("GET")+4:line.index("HTTP")])
except:
pass
counter = collections.Counter(clean_log)
# get the Top 50 most popular URLs
for count in counter.most_common(50):
print(str(count[1]) + " " + str(count[0]))
logfile.close()
从键盘获取用户输入
原文:https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
原始输入和输入
Python 中有两个函数可以用来从用户处读取数据:raw_input 和 input。您可以将结果存储到一个变量中。
原始输入
raw_input is used to read text (strings) from the user:
name = raw_input("What is your name? ")
type(name)
>>output
What is your name? spilcm
type 'str'>
投入
input is used to read integers
age = input("What is your age? ")
print "Your age is: ", age
type(age)
>>output
What is your age? 100
Your age is: 100
type 'int'>
更多阅读
http://www.python.org
Google 命令行脚本
原文:https://www.pythonforbeginners.com/code-snippets-source-code/google-command-line-script
概观
今天的帖子将展示如何用 Python(2.7 . x 版)制作 Google 命令行脚本
注意:从 2010 年 11 月 1 日起,谷歌网络搜索 API 已被正式否决。它将按照我们的弃用政策继续工作,但您每天可以提出的请求数量将受到限制。因此,我们鼓励您转向新的自定义搜索 API。”" "
为了向 Web 搜索 API 发出请求,我们必须导入我们需要的模块。
urllib2
Loads the URL response
urllib
To make use of urlencode
json
Google returns JSON
接下来,我们指定我们请求的 URL:http://ajax.googleapis.com/ajax/services/search/web?v=1.0&
为了使它更具交互性,我们将要求用户输入并将结果保存到一个名为“query”的变量中。
query = raw_input("What do you want to search for ? >> ")
通过加载 URL 响应来创建响应对象,包括我们上面要求的查询。
response = urllib2.urlopen (url + query ).read()
处理 JSON 字符串。data = json.loads(响应)
从这一点上,我们可以玩弄的结果
GoogleSearch.py
让我们看看完整的剧本
import urllib2
import urllib
import json
url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
query = raw_input("What do you want to search for ? >> ")
query = urllib.urlencode( {'q' : query } )
response = urllib2.urlopen (url + query ).read()
data = json.loads ( response )
results = data [ 'responseData' ] [ 'results' ]
for result in results:
title = result['title']
url = result['url']
print ( title + '; ' + url )
打开文本编辑器,复制并粘贴上面的代码。
将文件另存为 GoogleSearch.py 并退出编辑器。
运行脚本:$ python searchGoogle.py
What do you want to search for ? >> python for beginners
BeginnersGuide - Python Wiki; http://wiki.python.org/moin/BeginnersGuide
Python For Beginners; http://www.python.org/about/gettingstarted/
Python For Beginners; https://www.pythonforbeginners.com/
Python 中的图形
原文:https://www.pythonforbeginners.com/data-structures/graph-in-python
图是最重要的数据结构之一。图形用于表示电话网络、地图、社交网络连接等。在本文中,我们将讨论什么是图,以及如何用 Python 实现图。
什么是图?
在数学中,图被定义为一组顶点和边,其中顶点是特定的对象,边表示顶点之间的连接。顶点和边用集合来表示。
数学上,一个图 G 可以表示为 G= (V,E),其中 V 是顶点的集合,E 是边的集合。
如果一条边 E[i] 连接顶点 v1 和 v2,我们可以把这条边表示为 E[i] = (v1,v2)。
如何表示一个图形?
我们将使用下图中给出的图形来学习如何表示图形。

Graph in Python
为了表示一个图,我们必须找到图中的顶点和边的集合。
首先,我们将找到顶点集。为此,我们可以使用上图中给出的顶点创建一个集合。在图中,顶点被命名为 A、B、C、D、E 和 F,因此顶点集可以创建为 V={A,B,C,D,E,F}。
为了找到边的集合,首先我们将找到图中的所有边。你可以观察到图中有 6 条边,编号从 E ₁ 到 E₆ 。边 E[i] 可以被创建为元组(v1,v2 ),其中 v1 和 v2 是由 E[i] 连接的顶点。对于上图,我们可以将边表示如下。
- E₁ = (A,D)
- E₂ = (A,B)
- E₃ = (A,E)
- E₄ = (A,F)
- E₅ = (B,F)
- E₆ = (B,C)
边 E 的集合可以表示为 E= {E ₁ ,E ₂ ,E₃ ,E₄ ,E₅ ,E₆ }。
最后,图 G 可以表示为 G= (V,E)其中 V 和 E 是顶点和边的集合。
到目前为止,我们已经讨论了如何用数学方法表示一个图。你能想出一种在 python 程序中表示图形的方法吗?让我们来研究一下。
如何用 Python 表示一个图?
我们可以用邻接表来表示一个图。邻接表可以被认为是一个列表,其中每个顶点都存储了与之相连的所有顶点的列表。
我们将使用字典和列表在 python 中实现图的邻接表表示。
首先,我们将使用给定的顶点集创建一个 python 字典,其中所有顶点名称作为关键字,一个空列表(邻接表)作为它们的关联值。
之后,我们将使用给定的边集来完成每个顶点的邻接表,该邻接表已经使用字典的关键字来表示。对于每条边(v1,v2),我们会将 v1 添加到 v2 的邻接表中,将 v2 添加到 v1 的邻接表中。
这样,字典中的每个键(顶点)都将有一个关联的值(一个顶点列表),字典将用 python 表示整个图。
给定顶点和边的集合,我们可以如下用 python 实现一个图。
vertices = {"A", "B", "C", "D", "E", "F"}
edges = {("A", "D"), ("A", "B"), ("A", "E"), ("A", "F"), ("B", "F"), ("B", "C")}
graph = dict()
for vertex in vertices:
graph[vertex] = []
for edge in edges:
v1 = edge[0]
v2 = edge[1]
graph[v1].append(v2)
graph[v2].append(v1)
print("The given set of vertices is:", vertices)
print("The given set of edges is:", edges)
print("Graph representation in python is:")
print(graph)
输出:
The given set of vertices is: {'F', 'D', 'B', 'E', 'A', 'C'}
The given set of edges is: {('A', 'F'), ('A', 'B'), ('B', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'F')}
Graph representation in python is:
{'F': ['A', 'B'], 'D': ['A'], 'B': ['A', 'C', 'F'], 'E': ['A'], 'A': ['F', 'B', 'D', 'E'], 'C': ['B']}
在上面的输出中,您可以验证图形的每个关键点都有一个连接到它的顶点列表作为它的值。
结论
在本文中,我们讨论了图形数据结构。我们还讨论了图形的数学表示,以及如何用 python 实现它。要了解更多关于 Python 中数据结构的知识,可以阅读这篇关于 python 中链表的文章。
Python 中的图形操作
原文:https://www.pythonforbeginners.com/data-structures/graph-operations-in-python
图形是一种非线性数据结构,用于表示不同对象之间的联系。通常,图表用于表示地图、网络和社交媒体连接。在本文中,我们将研究如何在 Python 中执行不同的图形操作。我们将获取一个图,并将其作为一个运行示例来执行所有的图操作。
什么是不同的图形操作?
图通常以邻接表的形式提供。如果我们讨论上的运算,可能有如下的图形运算。
- 打印图形的所有顶点
- 打印图表的所有边
- 在图中插入一个顶点
- 在图中插入一条边
我们将在 python 中执行所有这些图形操作。为此,我们将使用下图中给出的图表。

Graph in Python
在执行图操作之前,我们将如下构建上述图的邻接表表示。
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Graph representation in python is:")
print(graph)
输出:
Graph representation in python is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
如何打印一个图的所有顶点
从上一篇关于 python 中的图的文章中,我们知道图的顶点是使用邻接矩阵(这是一个 python 字典)的键来表示的。因此,我们可以通过简单地打印邻接矩阵的键来打印图的所有顶点。为此,我们将如下使用 python 字典的 keys()方法。
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Graph representation in python is:")
print(graph)
vertices= list(graph.keys())
print("Vertices in the graph are:",vertices)
输出:
Graph representation in python is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
Vertices in the graph are: ['A', 'D', 'B', 'F', 'C', 'E']
如何打印图形的所有边
我们知道,图中的边是通过使用与每个顶点相关联的列表来表示的。每个顶点都存储一个与之相连的顶点列表。我们将遍历每个顶点 v1,并为存在于与 v1 相关联的列表中的每个顶点创建边(v1,v2)。
记住,当打印边时,会有重复,因为每当顶点 v2 出现在与 v1 相关联的列表中时,v1 也会出现在与 v2 相关联的列表中。因此,在打印边缘时,将打印(v1,v2)和(v2,v1)两者,这引入了冗余,因为(v1,v2)和(v2,v1)两者表示相同的边缘。
为了克服这个问题,我们将把任何边(v1,v2)存储为一个无序集。这样,(v1,v2)将与(v2,v1)相同。之后,我们将创建一个边列表。在向列表中插入任何新边之前,我们将首先检查该边是否存在于列表中。如果列表中已经存在任何边,我们将不会插入任何重复的边。
上述过程可以用 python 实现如下。
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Graph representation in python is:")
print(graph)
edges = []
for vertex in graph:
for adjacent_vertex in graph[vertex]:
edge = {vertex, adjacent_vertex}
if edge not in edges:
edges.append(edge)
print("Edges in the graph are:", edges)
输出:
Graph representation in python is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
Edges in the graph are: [{'B', 'A'}, {'A', 'D'}, {'A', 'E'}, {'A', 'F'}, {'B', 'F'}, {'B', 'C'}]
如何在图中插入一个顶点
我们知道顶点是用邻接表的关键字来表示的。为了将一个顶点插入到图中,我们将把这个顶点作为一个键插入到图中,用一个空列表作为它的关联值。空列表表示当前顶点没有连接到任何其他顶点。我们可以这样实现它。
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Original Graph representation is:")
print(graph)
# insert vertex G
graph["G"] = []
print("The new graph after inserting vertex G is:")
print(graph)
输出:
Original Graph representation is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
The new graph after inserting vertex G is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A'], 'G': []}
如何在图形中插入一条边
在图中插入边比打印边要简单得多。我们知道每个顶点包含一个它所连接的顶点列表。因此,为了插入边(v1,v2),我们将简单地将顶点 v1 插入到与 v2 相关联的顶点列表中,并将 v2 插入到与顶点 v1 相关联的顶点列表中。
这样,将建立 v1 连接到 v2,v2 连接到 v1。因此,顶点(v1,v2)将被添加到图形中。我们可以这样实现它。
graph ={'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A'], 'G': []}
print("Original Graph representation is:")
print(graph)
# insert vertex (D,G)
graph["D"].append("G")
graph["G"].append("D")
print("The new graph after inserting edge (D,G) is:")
print(graph)
输出:
Original Graph representation is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A'], 'G': []}
The new graph after inserting edge (D,G) is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A', 'G'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A'], 'G': ['D']}
结论
在本文中,我们用 python 实现了不同的图形操作。想了解更多关于其他数据结构的知识,可以阅读这篇关于 python 中链表的文章。
与操作系统同乐。穿蟒蛇皮走路
原文:https://www.pythonforbeginners.com/code-snippets-source-code/having-fun-with-os-walk-in-python
概观
**OS.walk()** generate the file names in a directory tree by walking the tree either
top-down or bottom-up.
For each directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
**Paths**
root : Prints out directories only from what you specified
dirs : Prints out sub-directories from root.
files: Prints out all files from root and directories
walkFileSystem.py
Open an text editor , copy & paste the code below.
Save the file as walkFileSystem.py and exit the editor.
Run the script:
$ python walkFileSystem.py
import os
os.system("clear")
print "-" * 80
print "OS Walk Program"
print "-" * 80
print "
"
print "Root prints out directories only from what you specified"
print "-" * 70
print "Dirs prints out sub-directories from root"
print "-" * 70
print "Files prints out all files from root and directories"
print "-" * 70
print "This program will do an os.walk on the folder that you specify"
print "-" * 70
path = raw_input("Specify a folder that you want to perform an 'os.walk' on: >> ")
for root, dirs, files in os.walk(path):
print root
print "---------------"
print dirs
print "---------------"
print files
print "---------------"
More reading can be found [here](https://docs.python.org/2/library/os.html "library_os")
开发者们好。认识 Python。增长之王
原文:https://www.pythonforbeginners.com/basics/hello-developers-meet-python-king-growth
在很大程度上,很难将一种语言加冕为开发世界中标准使用的最高领导者。没有一种语言能独占鳌头,尽管有些开发人员肯定更喜欢其中的一种或几种。增长也不足为奇,尤其是在今天这个高度虚拟化和数字化的世界。人工智能、自动化、机器学习、移动和网页设计等技术都有利于开发,这反过来又满足了对更多程序员和开发专业人员的需求。
也就是说,如果只有一种语言因其不可思议的潜力而让你选择学习,那就是 Python。为什么?我们将仔细观察 Python 目前令人难以置信的增长,尤其是在高收入和开发密集型国家。
Python,至少现在,可以被认为是语言和开发领域的增长之王。崇高的主张?不信?没问题,让我们深入研究一下,看看我们为什么要说这样的话。
什么是“高收入”国家?
首先,我们需要定义“高收入”国家,以及在审视当前趋势和统计数据时,为什么这是一个重要的区别。
高收入国家包括那些工资或薪水达到行业平均水平的国家;通常这在 60,000 美元到 140,000 美元之间,但取决于所讨论的国家。
最常见的国家包括美国、英国、德国和加拿大。请记住,这些并不是全球软件开发行业中唯一的主要贡献者。同样具有影响力的还有俄罗斯、中国、巴西和其他许多国家——尽管它们在薪资和工资待遇方面确实有所欠缺。
虽然 Python 在所有这些市场都显示出增长,但高收入市场显示出最有影响力的数字。
增长是如何衡量的
正如大卫·罗宾逊在 Stack Overflow 博客上报道的,你可以使用平台的趋势工具来查看和衡量各种开发语言的增长,Python 也不例外。
从 2011 年开始,在五种主要语言(也包括 CSS、HTML、Android 和 JQuery)中,Python 在高收入国家取得了令人难以置信的增长。2017 年 6 月,Python 成为高收入国家中 Stack Overflow 上访问量最大的标签。与 2012 年相比,这是一个令人印象深刻的景象,当时它是五种语言中访问量最少的标签。短短五年间,这种语言的受欢迎程度已经翻了一倍多。
罗宾逊继续解释了发生这种变化的一些潜在原因。例如,由于教育目的,Java 有季节性流量。然而,不可否认的是 Python 的发展。
然而,他并不是唯一有这一发现的人。其他人也注意到了 Python 在过去受欢迎程度的上升,包括2014 年 Dice 的一份报告。
著名的 Python 开发者 Jeff Knupp 似乎认为这种增长正在发生——并且正在加速——仅仅是因为一个特性, Python 的缓冲协议。Knupp 认为,低级 API 提供了对内存和大量存储数据的零拷贝访问,这非常适合数据科学家。为什么这很重要?嗯,因为现在几乎一切都是由大数据、分析、智能和机器学习驱动的。这就解释了为什么我们会关注不仅使这些过程更容易,而且更有效的语言。
不过,这种情况会很快改变吗?再次查看堆栈溢出趋势报告,很容易发现 Python 也将成为 2018 年最受欢迎的工具之一。
如何参与 Python?
显然,如果您过去考虑过学习或使用 Python,现在是时候加入了。例如,Python 开发人员的平均工资正在攀升。2014 年起价约为 8.5 万美元,在硅谷市场则飙升至 12 万美元甚至更高。
从我们免费的初学者教程和编码指南开始。您将学习该语言提供的好处,如何设置和使用该环境,以及如何使用像 Django 这样的框架。它通过引导你完成 6 个项目来结束,你可以在你的空闲时间完成,教你如何处理和塑造代码。
从那以后,就看你的了。当然,我们建议在树屋上查看课程。但是你可以通过任何你喜欢的训练或养生法。在免费教程结束时,你应该有足够的知识来决定下一步去哪里,如果不是用这种语言开发基本的应用程序。
Python 初学者的推荐培训课程
如何运行您的 Python 脚本
原文:https://www.pythonforbeginners.com/development/how-run-your-python-scripts
您的 Python 代码可以位于代码编辑器、IDE 或文件中。而且,除非你知道如何执行你的 Python 脚本,否则它不会起作用。
在这篇博文中,我们将看看执行 Python 代码和脚本的 7 种方式。无论您的操作系统是什么,您的 Python 环境是什么,或者您的代码在什么位置,我们都将向您展示如何执行这段代码!
目录
- 交互式运行 Python 代码
- Python 脚本是如何执行的
- 如何运行 Python 脚本
- 如何使用命令行运行 Python 脚本
- 如何交互式运行 Python 代码
- 从文本编辑器运行 Python 代码
- 从 IDE 中运行 Python 代码
- 如何从文件管理器运行 Python 脚本
- 如何从另一个 Python 脚本运行 Python 脚本
在哪里运行 Python 脚本以及如何运行?
您可以从以下位置运行 Python 脚本:
- 操作系统命令行(也称为外壳或终端)
- 在 Anaconda 上运行特定 Python 版本的 Python 脚本
- 使用 Crontab
- 使用另一个 Python 脚本运行一个 Python 脚本
- 使用文件管理器
- 使用 Python 交互模式
- 使用 IDE 或代码编辑器
交互式运行 Python 代码
要启动 Python 代码的交互式会话,只需打开终端或命令行并输入 Python(或 Python 3,取决于您的 Python 版本)。一旦你按下回车键,你将进入交互模式。
以下是在 Windows、Linux 和 MacOS 中进入交互模式的方法。
Linux 上的交互式 Python 脚本模式
打开你的终端。
它应该看起来像这样
$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
按“回车”后进入 Python 脚本交互模式。
Mac OSX 上的交互式 Python 脚本模式
在 Mac OS 上启动交互式 Python 脚本模式与 Linux 非常相似。下图显示了 Mac OS 上的交互模式。

Windows 上的交互式 Python 脚本模式
在 Windows 上,进入你的命令提示符,写“python”。一旦您按下 enter 键,您应该会看到类似这样的内容:

交互式运行 Python 脚本
使用交互式 Python 脚本模式,您可以编写代码片段并执行它们,以查看它们是否给出所需的输出或是否失败。
以下面的 for 循环为例。

我们的代码片段被编写为打印所有内容,包括 0 到 5。所以,你在 print(i)之后看到的是这里的输出。
要退出交互式 Python 脚本模式,请编写以下内容:
>>>exit()
然后,按回车键。您应该会回到最初启动的命令行屏幕。
还有其他方法可以退出交互式 Python 脚本模式。在 Linux 上,你可以简单地按 Ctrl + D,而在 Windows 上,你需要按 Ctrl + Z + Enter 来退出。
请注意,当您退出交互模式时,您的 Python 脚本不会保存到本地文件。
Python 脚本是如何执行的?
一种直观显示执行 Python 脚本时发生的情况的好方法是使用下图。该块代表我们编写的 Python 脚本(或函数),其中的每个块代表一行代码。

当您运行这个 Python 脚本时,Python 解释器从上到下执行每一行。
这就是 Python 解释器执行 Python 脚本的方式。
但不是这样的!还有很多事情发生。
Python 解释器如何运行代码的流程图
第一步:你的脚本或。py 文件编译并生成二进制格式。这种新的形式要么是。pyc 或. pyo。

步骤 2:生成的二进制文件,现在由解释器读取以执行指令。
把它们想象成一堆导致最终结果的指令。
检查字节码有一些好处。而且,如果你的目标是把自己变成一个专业的 Python 高手,你可能想要学习和理解字节码来编写高度优化的 Python 脚本。
您还可以使用它来理解和指导您的 Python 脚本的设计决策。你可以看看某些因素,理解为什么有些函数/数据结构比其他的快。
如何运行 Python 脚本?
要使用命令行运行 Python 脚本,首先需要将代码保存为本地文件。
让我们再次以本地 Python 文件为例。如果你把它保存到本地。名为 python_script.py 的 py 文件。
有许多方法可以做到这一点:
- 从命令行创建一个 Python 脚本并保存它
- 使用文本编辑器或 IDE 创建 Python 脚本并保存它
从代码编辑器中保存 Python 脚本非常容易。基本上就像保存一个文本文件一样简单。
但是,要通过命令行来完成,需要几个步骤。
首先,转到命令行,将工作目录更改为您希望保存 Python 脚本的位置。
进入正确的目录后,在终端中执行以下命令:
$ sudo nano python_script.py
一旦您按下 enter,您将进入一个命令行界面,如下所示:

现在,您可以在这里编写 Python 代码,并使用命令行轻松运行它。
如何使用命令行运行 Python 脚本?
Python 脚本可以通过命令行界面使用 Python 命令运行。确保您指定了脚本的路径或具有相同的工作目录。要执行您的 Python 脚本(python_script.py ),请打开命令行并编写 python3 python_script.py
如果您的 python 版本是 python2.x,请用 Python 替换 python3。
以下是我们保存在 python_script.py 中的内容
for i in range(0,5):
print(i)
并且,命令行上的输出如下所示

比方说,我们想要保存 Python 代码的输出,即 0,1,2,3,4——我们使用了一种叫做管道操作符的东西。
在我们的情况下,我们要做的就是:
$python python_script.py > newfile.txt
并且,会创建一个名为“newfile.txt”的文件,其中保存了我们的输出。
如何交互式运行 Python 代码
有 4 种以上的方法可以交互运行 Python 脚本。在接下来的几节中,我们将看到执行 Python 脚本的所有主要方式。
使用导入运行 Python 脚本
我们都非常频繁地使用导入模块来加载脚本和库。您可以编写自己的 Python 脚本(比如 code1.py)并将其导入到另一个代码中,而无需再次在新脚本中编写整个代码。
下面是如何在新的 Python 脚本中导入 code1.py。
>>> import code1
但是,这样做意味着将 code1.py 中的所有内容都导入到 Python 代码中。这不是问题,直到你开始在你的代码必须针对性能、可伸缩性和可维护性进行优化的情况下工作。
比方说,我们在 code1 中有一个小函数,它可以绘制一个漂亮的图表,例如 chart_code1()。而且,该函数是我们希望导入整个 code1.py 脚本的唯一原因。我们不必调用整个 Python 脚本,而是可以简单地调用函数。
这是你通常会怎么做
>>> from code1 import chart_code1
而且,您应该能够在新的 Python 脚本中使用 chart_code1,就像它出现在您当前的 Python 代码中一样。
接下来,让我们看看导入 Python 代码的其他方法。
使用和 importlib 运行 Python 代码
importlib 的 import_module()允许您导入和执行其他 Python 脚本。
它的工作方式非常简单。对于我们的 Python 脚本 code1.py,我们要做的就是:
import importlib
import.import_module(‘code1’)
没必要补充。py in import_module()。
让我们看一个例子,我们有复杂的目录结构,我们希望使用 importlib。我们要运行的 Python 代码的目录结构如下:
级别 1
|
+–_ _ init _ _。巴拉圭
–二级
|
+–_ _ init _ _。巴拉圭
–level 3 . py
在这种情况下,如果你认为你可以做 import lib . import _ module(" level 3 "),你会得到一个错误。这被称为相对导入,其方法是使用带有 anchor explicit 的相对名称。
因此,要运行 Python 脚本 level3.py,您可以
importlib.import_module(“.level3”, “level1.level”)
或者你可以
importlib.import_module(“level1.level2.level3”).
使用 runpy 运行 Python 代码
Runpy 模块定位并执行 Python 脚本,而不导入它。用法非常简单,因为您可以轻松地在 run_module()中调用模块名。
使用 runpy 执行我们的 code1.py 模块。这是我们要做的。
>>> import runpy
>>> runpy.run_module(mod_name=”code1”)
动态运行 Python 代码
我们将看看 exec()函数来动态执行 Python 脚本。在 Python 2 中,exec 函数实际上是一个语句。
下面是它如何帮助你在字符串的情况下动态执行 Python 代码。
>>> print_the_string = ‘print(“Dynamic Code Was Executed”)’
>>> exec(print_the_string)
动态代码已执行
但是,使用 exec()应该是最后的手段。由于速度慢且不可预测,请尝试看看是否有其他更好的替代方案。
从文本编辑器运行 Python 脚本
要使用 Python 文本编辑器运行 Python 脚本,您可以使用默认的“运行”命令或使用热键,如 Function + F5 或简单的 F5(取决于您的操作系统)。
下面是一个在空闲状态下执行 Python 脚本的例子。

资料来源:pitt.edu
但是,请注意,您不能像通常从命令行界面执行那样控制虚拟环境。
这就是 ide 和高级文本编辑器远胜于代码编辑器的地方。
从 IDE 中运行 Python 脚本
当从 IDE 执行脚本时,您不仅可以运行您的 Python 代码,还可以调试它并选择您想要运行它的 Python 环境。
虽然 IDE 的 UI 界面可能会有所不同,但是保存、运行和编辑代码的过程非常相似。
如何从文件管理器运行 Python 脚本
如果有一种只需双击就能运行 Python 脚本的方法呢?您实际上可以通过创建代码的可执行文件来做到这一点。例如,在 Windows 操作系统的情况下,您可以简单地创建 Python 脚本的. exe 扩展名,并通过双击它来运行它。
如何从另一个 Python 脚本运行 Python 脚本
虽然我们还没有提到这一点,但是,如果你回去阅读,你会发现你可以:
- 通过调用另一个 Python 脚本的命令行运行 Python 脚本
- 使用类似 import 的模块加载 Python 脚本
就是这样!
关键外卖
- 您可以在交互和非交互模式下编写 Python 代码。一旦退出交互模式,数据就会丢失。所以,sudo nano your _ python _ filename . py 吧!
- 您还可以通过 IDE、代码编辑器或命令行运行 Python 代码
- 有不同的方法可以导入 Python 代码并将其用于另一个脚本。明智地挑选,看看优缺点。
- Python 读取您编写的代码,将其翻译成字节码,然后用作指令——所有这些都发生在您运行 Python 脚本时。因此,学习如何使用字节码来优化您的 Python 代码。
如何用 Python 访问各种 Web 服务
原文:https://www.pythonforbeginners.com/python-on-the-web/how-to-access-various-web-services-in-python
概观
学习 Python 的一个非常好的方法是尝试使用各种 Web 服务
API。
如何访问 Youtube、Vimeo、Twitter 等网络服务?
为了回答这个问题,我们首先要了解一些关于 API、
JSON、数据结构等等的知识。
入门指南
对于那些关注我们的人来说,希望你已经获得了一些基本的 Python 知识。对于还没有看过的人,我建议你开始阅读我们网站顶部的
页面,或者点击下面你想让
了解更多的链接。
API:应用编程接口
API 是一种协议,旨在被软件组件用作相互通信的接口。API 是一组编程指令和
标准,用于访问基于 web 的软件应用程序(如上所述)。
借助 API,应用程序可以在没有任何用户知识或
干预的情况下相互对话。
通常,像谷歌、Vimeo 和 Twitter 这样的公司向公众发布它的 API
,这样开发者就可以开发基于它的服务的产品。
重要的是要知道 API 是软件到软件的接口,而不是用户接口。
API 密钥
互联网上的许多服务(如 Twitter、脸书..)要求你
有一个“API 密匙”。
应用编程接口密钥(API key)是由调用 API 的
计算机程序传入的代码,用于向网站标识调用程序、其开发者、
或其用户。
API 密钥用于跟踪和控制 API 的使用方式,例如
防止恶意使用或滥用 API。
API 密钥通常既作为唯一的标识符,又作为用于
认证的秘密令牌,并且通常具有一组对与之相关联的 API
的访问权限。
当我们与一个 API 交互时,我们经常以一种叫做 JSON 的形式得到响应。
Json
让我们快速而不深入地了解一下 JSON 是什么。JSON (JavaScript Object Notation)是一种紧凑的、基于文本的格式,用于计算机交换数据。
它建立在两个结构之上:
——名称/值对的集合
–有序的值列表。JSON 采用这些形式:对象、数组、值、字符串、数字
对象
–无序的名称/值对集合。
–以{开始,以}结束。
–每个名称后跟:(冒号)
–名称/值对由(逗号)分隔。
数组
–有序的数值集合。
–以【开始,以】结束。
–值由(逗号)分隔。
值
–可以是双引号中的字符串,数字,或真或假或空,
或者是对象或数组。
字符串
–零个或多个 Unicode 字符的序列,用双引号
括起来,使用反斜杠转义。
数字
–整数、长整型、浮点型
访问 Web 服务
Python 为我们提供了与 json 交互的 json 和 simplejson 模块。
这个时候,我们应该知道 API 是什么,它的作用是什么。另外,我们现在
知道了 JSON 的基础知识。
为了开始访问 web 服务,我们首先需要找到一个 URL 来调用 API。
在我们获得 URL 之前,我真的建议你阅读提供的文档
(如果有的话)。
文档描述了如何使用 API,并包含了关于我们如何与之交互的重要信息。
我们需要的 URL 通常可以在公司网站
上找到,与 API 文档在同一个地方。
举个例子:
YouTube
http://g data . YouTube . com/feeds/API/standard feeds/most _ popular?v=2 & alt=json
http://vimeo.com/api/v2/video/video_id.output
Reddit
http://www.reddit.com/user/spilcm/comments/.json
请不要认为这些会过时,因此,请确认您拥有最新的
版本。
当你有了一个 URL 并且你已经阅读了提供的文档,我们从
导入我们需要的模块开始。
我需要什么模块?
我在使用 JSON 时通常使用的模块有:
–请求
–JSON(或simple JSON)
–pprint
我曾经使用 urllib2 模块来打开 URL,但是自从 Kenneth Reitz
给了我们请求模块,我就让这个模块来完成我的大部分 HTTP 任务。
处理数据
一旦您知道您需要哪个 URL 并导入了必要的模块,我们就可以使用请求模块来获取 JSON 提要。
r = requests . get(" http://www . Reddit . com/user/spil cm/about/。json")
r.text
您可以将输出复制并粘贴到 JSON 编辑器中,以便更容易地查看数据。
我使用http://jsoneditoronline.org/,但是任何 JSON 编辑器都应该做这项工作。
下一步是将 JSON 输出转换成 Python 字典。
转换数据
这将获取 JSON 字符串并使其成为一个字典:
json.loads(r.text)
注意:还可以使用
json.dumps()将 python 对象序列化为 JSON。
然而,这不是我们现在想做的。
遍历结果
我们知道有一个 python 字典,我们可以开始使用它来获得我们想要的结果。
一种常见的方法是循环结果,得到你感兴趣的数据。
这有时可能是棘手的部分,你需要仔细观察
结构是如何呈现的。
同样,使用 Json 编辑器会更容易。
使用 YouTube API
此时,我们应该有足够的知识和信息来创建一个程序
该程序将显示 YouTube 上最受欢迎的视频。
#Import the modules
import requests
import json
# Get the feed
r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2&alt=jsonc")
r.text
# Convert it to a Python dictionary
data = json.loads(r.text)
# Loop through the result.
for item in data['data']['items']:
print "Video Title: %s" % (item['title'])
print "Video Category: %s" % (item['category'])
print "Video ID: %s" % (item['id'])
print "Video Rating: %f" % (item['rating'])
print "Embed URL: %s" % (item['player']['default'])
print
看看我们如何遍历结果来获得我们想要的键和值。
YouTube、Vimeo 和 Twitter 示例
如何在 Python 中使用 YouTube API
如何在 Python 中使用 Vimeo API
各种 Web 服务的 API 文档
YouTube
https://developers . Google . com/YouTube/2.0/developers _ guide _ JSON
http://developer.vimeo.com/apis/
推特
https://dev.twitter.com/docs/api/1.1/overview
Reddit
http://www.reddit.com/dev/api
如何在 Python 中向集合中添加元素
原文:https://www.pythonforbeginners.com/basics/how-to-add-an-element-to-a-set-in-python
python 中的集合用于存储唯一的元素或对象。与元组或列表等其他数据结构不同,集合不允许向其中添加重复值。在本文中,我们将研究用 python 向集合中添加元素的不同方法。我们还将了解一些不允许向集合中添加特定类型对象的用例。
使用 Add()方法将元素添加到集合中
add()方法用于向集合中添加新值。在集合上调用时,add()方法将一个要添加到集合中的元素作为输入参数,并将其添加到集合中。当输入元素已经存在于集合中时,什么都不会发生。成功执行后,add()方法返回 None。
我们可以使用 add()方法向集合中添加一个元素,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
mySet.add(6)
print("Set after adding 6 to it:", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
Set after adding 6 to it: {1, 2, 3, 4, 5, 6}
当我们向集合中添加重复元素时,集合保持不变。你可以在下面的例子中看到。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
mySet.add(5)
print("Set after adding 5 to it:", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
Set after adding 5 to it: {1, 2, 3, 4, 5}
如何向集合中添加多个元素
我们将使用 update()方法向一个集合中添加多个元素。update()方法接受一个或多个 iterable 对象,如 python 字典、元组、列表或集合,并将 iterable 的元素添加到现有集合中。
我们可以将列表元素添加到集合中,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myList = [6, 7, 8]
print("List of values is:", myList)
mySet.update(myList)
print("Set after adding elements of myList:", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
List of values is: [6, 7, 8]
Set after adding elements of myList: {1, 2, 3, 4, 5, 6, 7, 8}
要添加两个或更多列表中的元素,我们只需将每个列表作为输入参数传递给 update()方法,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myList1 = [6, 7, 8]
myList2 = [9, 10]
print("First List of values is:", myList1)
print("Second List of values is:", myList2)
mySet.update(myList1, myList2)
print("Set after adding elements of myList1 and myList2 :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
First List of values is: [6, 7, 8]
Second List of values is: [9, 10]
Set after adding elements of myList1 and myList2 : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
就像列表一样,我们可以使用与列表相同的语法从一个或多个元组或集合中添加元素。
当我们试图使用 update()方法将一个 python 字典添加到集合中时,只有字典的键被添加到集合中。这可以在下面的例子中观察到。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myDict = {6: 36, 7: 49, 8: 64}
print("Dictionary is:", myDict)
mySet.update(myDict)
print("Set after updating :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
Dictionary is: {6: 36, 7: 49, 8: 64}
Set after updating : {1, 2, 3, 4, 5, 6, 7, 8}
要将字典中的值添加到集合中,我们必须使用 dict.values()方法显式传递值列表,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myDict = {6: 36, 7: 49, 8: 64}
print("Dictionary is:", myDict)
mySet.update(myDict.values())
print("Set after updating :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
Dictionary is: {6: 36, 7: 49, 8: 64}
Set after updating : {64, 1, 2, 3, 4, 5, 36, 49}
我们还可以使用解包操作符*向一个集合中添加多个元素。为此,我们将首先解包当前集合和包含要添加到集合中的元素的对象。解包后,我们可以使用所有元素创建一个新的集合,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myList = [6, 7, 8]
print("List of values is:", myList)
mySet = {*mySet, *myList}
print("Set after updating :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
List of values is: [6, 7, 8]
Set after updating : {1, 2, 3, 4, 5, 6, 7, 8}
将对象添加到集合
就像单个元素一样,我们也可以使用 add()方法将对象添加到集合中。唯一的条件是我们只能添加不可变的对象。例如,我们可以使用 add()方法向列表中添加一个元组,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myTuple = (6, 7, 8)
print("List of values is:", myTuple)
mySet.add(myTuple)
print("Set after updating :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
List of values is: (6, 7, 8)
Set after updating : {1, 2, 3, 4, 5, (6, 7, 8)}
当我们试图向集合中添加一个可变对象(比如列表)时,它会引发 TypeError。这是因为可变对象是不可哈希的,不能添加到集合中。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myList = [6, 7, 8]
print("List of values is:", myList)
mySet.add(myList)
print("Set after updating :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
List of values is: [6, 7, 8]
Least distance of vertices from vertex 0 is:
{0: 0, 1: 1, 2: 2, 3: 1, 4: 2, 5: 3}
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 5, in <module>
mySet.add(myList)
TypeError: unhashable type: 'list'
TypeError 可以通过使用除了块之外的 python try 的异常处理来处理。
如何在 Python 中将字符串作为元素添加到集合中
我们可以使用 add()方法将整个字符串添加到集合中,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myStr="PythonForBeginners"
print("String is:", myStr)
mySet.add(myStr)
print("Set after updating :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
String is: PythonForBeginners
Set after updating : {1, 2, 3, 4, 5, 'PythonForBeginners'}
为了将字符串的字符添加到集合中,我们将使用 update()方法,如下所示。
mySet = set([1, 2, 3, 4, 5])
print("Original Set is:", mySet)
myStr="PythonForBeginners"
print("String is:", myStr)
mySet.update(myStr)
print("Set after updating :", mySet)
输出:
Original Set is: {1, 2, 3, 4, 5}
String is: PythonForBeginners
Set after updating : {1, 2, 3, 4, 5, 'P', 'y', 'F', 'r', 'g', 'B', 's', 'i', 'o', 'h', 'n', 't', 'e'}
结论
在本文中,我们看到了用 python 向集合中添加一个或多个元素的各种方法。我们还看到了如何向集合中添加字符串或其他不可变对象。请继续关注更多内容丰富的文章。
如何在 Python 中最好地使用 Try-Except
原文:https://www.pythonforbeginners.com/error-handling/how-to-best-use-try-except-in-python
异常处理允许我们对变量施加约束,以在计算机程序中实现我们的业务逻辑,它还使我们能够编写一个健壮的程序,该程序可以处理执行过程中出现的不同类型的错误。在 python 中,我们使用 try-except 块来实现异常处理。在本文中,我们将通过查看插图来了解一些编写高效 python 程序的方法,以便最好地使用 try——除了在 python 中。所以,让我们深入研究一下。
使用 raise 关键字手动引发异常
python 程序在出错时会自动抛出内置异常,但我们也可以使用 raise 关键字手动引发内置异常。通过使用 raise 关键字抛出内置异常,我们可以使用内置异常对变量施加约束,以确保程序在逻辑上是正确的。这里要记住的一点是,一个程序可能不会抛出任何错误,但如果不对变量应用适当的约束,它可能会输出一个不切实际的值。因此,我们可以使用 raise 关键字在 python try-except 块中抛出异常来强制约束。
例如,假设我们想根据一个人的年龄来计算他的出生年份,我们可以这样做:
age= 10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
10
Year of Birth is:
2011
我们可以看到,对于一个 10 岁的人来说,程序给出了正确的输出。现在我们将尝试给程序输入一个负的年龄,看看会发生什么。
age= -10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
-10
Year of Birth is:
2031
在上面的输出中,我们可以看到程序已经成功执行,并且给出了一个逻辑上不可能的输出,因为没有人能够知道他的出生年份。因此,当 age 为负时,我们将使用 try-except 错误处理代码手动引发一个错误,然后我们将如下所示显示正确的输出。
try:
age= -10
print("Age is:")
print(age)
if age<0:
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except ValueError:
print("Input Correct age.")
输出:
Age is:
-10
Input Correct age.
这里可以看到,当输入年龄为负值时,程序手动引发ValueError,错误由 except 块中的代码处理。我们也可以自己定义定制的异常来实现约束,如下一节所述。
使用自定义异常
为了加强约束,我们可以通过定义类来声明自己的异常,这些类应该是任何内置异常的子类。通过这种方式,我们可以创建一个名称对我们的约束更有意义的异常,然后我们可以通过检查和引发自定义异常来对变量实施约束。
在下面的例子中,我们通过继承 python 异常类来定义NegativeAgeError异常类。每当输入中的 age 值为负时,就会引发名为NegativeAgeError的自定义错误,然后由 except 块中的代码处理该错误。只要输入年龄的正值,程序就会正常工作。
class NegativeAgeError(Exception):
pass
try:
age= -10
print("Age is:")
print(age)
if age<0:
raise NegativeAgeError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except NegativeAgeError:
print("Input Correct age.")
输出:
Age is:
-10
Input Correct age
在 python 中使用 try-except 区分不同类型的错误
在许多情况下,我们希望以不同的方式处理不同的运行时和自定义异常。我们可能想要找出在程序执行期间发生了哪个异常,或者我们可能想要在不同的异常发生时执行不同的任务。在这些情况下,我们可以通过将异常名称作为 except 块的参数来单独捕获每个异常,如下例所示,然后我们可以针对该特定异常执行 except 块中给出的语句。
try:
age= -10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except AssertionError:
print("Input Correct age.")
except ValueError:
print("ValueError occured")
except NameError:
print("NameError occurred")
except:
print("Some other exception occurred")
在上面的程序中,我们已经明确地将AssertionError、ValueError和NameError与其他类型的异常区分开来,并且我们已经明确地处理了它们。在区分异常时必须记住,最一般的异常必须在 except 块中最后写入,最具体的异常必须在 except 块中首先写入。否则将会生成不可达的代码并导致错误。
例如,在 python 中使用 try-except 来区分异常的方法是错误的。
try:
age= -10
print("Age is:")
print(age)
raise IOError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except:
print("Some other exception occurred")
except AssertionError:
print("Input Correct age.")
except ValueError:
print("ValueError Occured")
except NameError:
print("NameError occurred")
输出:
File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-f6b48848354a>", line 1, in <module>
runfile('/home/aditya1117/untitled0.py', wdir='/home/aditya1117')
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/aditya1117/untitled0.py", line 8
print(yearOfBirth)
^
SyntaxError: default 'except:' must be last
我们可以看到,当我们在特定异常之前使用更一般的 except 块时,程序中会出现语法错误。
在 python 中使用 try-except 对异常进行分组
在编写程序时,可能会有很多情况,我们希望以相同的方式处理两个或更多的异常。我们可以在 python 中将某些类型的异常分组,然后通过将组中的每个异常作为参数传递给 except 块,由相同的错误处理代码来处理它们。
在下面的例子中,我们将AssertionError、ValueError和NameError分组在一个 except 块中,当任何错误发生时,将执行相同的代码。
try:
age= -10
print("Age is:")
print(age)
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except (AssertionError,ValueError,NameError):
print("AssertionError or ValueError or NameError has occurred.")
except:
print("Some other exception occurred")
最终块
在一个程序中,无论在什么情况下,每次程序终止前都可能有一些语句要执行。在这种情况下,我们可以将语句放在 Finally 块中。无论 try 块中是否出现任何错误/异常,Finally 块都会执行。当 try 块引发异常时,首先执行 except 块中的代码,然后执行 finally 块中的代码。否则,当没有发生任何错误时,在 try 块之后执行 Finally 块。
例如,当我们执行 python 写文件操作时,文件总是需要在程序终止前关闭,这样数据才不会丢失。在这种情况下,我们可以编写代码来关闭 Finally 块中的文件,如下所示。
try:
file_ptr=open("filename.txt","w")
file_ptr.write("This is PythonForBeginners.com")
except (IOError):
print("IOError has occurred.")
except:
print("Some other exception occurred")
finally:
file_ptr.close()
结论
在本文中,我们已经看到了如何在 python 中最好地使用 try-except,方法是应用像自定义异常这样的方法,对异常进行分组并区分不同的异常。请继续关注更多内容丰富的文章。
如何在 Python 中清除文本文件
原文:https://www.pythonforbeginners.com/basics/how-to-clear-a-text-file-in-python
虽然程序经常被用来创建文件,但有时程序员也需要擦除文件数据。幸运的是,有多种方法可以清除文件中的文本。在这篇文章中,我们将使用一些简单的例子来演示如何在 Python 中清除文本文件。
通过使用 Python 的一些标准工具,我们可以打开、读取和清除文本文件。我们还将学习如何使用切片符号从文本文件中删除特定的行。
Python 简化了文件处理的过程,产生了更简洁的程序。作为学习本指南的结果,您将理解 Python 如何清除文本文件和删除数据行。
在写入模式下使用 open()函数清除文本文件
以写模式打开文件将自动删除文件内容。 open ()函数有两个参数,我们想要打开的文本文件和我们打开它的模式。
以写模式打开文件会清除其中的数据。此外,如果指定的文件不存在,Python 将创建一个新文件。删除文件最简单的方法是使用 open()并在写入模式下将它赋给一个新变量。
file_to_delete = open("info.txt",'w')
file_to_delete.close()
带有语句的 Python 简化了异常处理。使用和在写模式下打开一个文件也将清除其数据。pass 语句完成了该示例。
# clear the data in the info file
with open("info.txt",'w') as file:
pass
如何用 truncate()方法清除文件
truncate()方法减小文档的大小。此方法采用一个可选参数来设置文件的新大小。如果没有提供参数,则文件保持不变。
试图将文件截断到大于其原始大小可能会产生意外的结果。例如,如果截断大小超过原始文件大小,程序可能会在文件末尾添加空白。
我们将使用一个演示文本文件来测试 Python 截断文件的能力:
info.txt
吉多·范·罗苏姆在 1991 年创造了 Python。
Python 是一种通用编程语言。
Python 的优势之一是可读性。
with open("info.txt",'r+') as file:
file.truncate(16)
# read the file’s contents
with open("info.txt", 'r') as file:
lines = file.readlines()
for line in lines:
print(line)
输出
Guido van Rossum
在上面的例子中,truncate()方法将文件缩减为文本的前 16 个字符。请注意,我们以读写模式打开了该文件。为了使 truncate 方法起作用,这是必要的。
通过将值 0 传递给 truncate()方法,可以完全清除文本文件。
with open("example.txt",'r+') as file:
file.truncate(0)
上面的 Python 代码将清除一个文本文件的内容。以这种方式使用 truncate()方法会将文件大小减小到 0,并删除文件中包含的所有内容。
使用 Python 列表切片清除文本文件
使用 Python 切片符号,可以检索列表、字符串或元组的子集。使用这个 Python 特性,我们可以定义给定子集的开始和结束索引。
切片表示法使用一种特殊的语法来查找一系列值的子集。以下示例显示了切片标记法的工作原理。通过定义切片的开始、结束和步骤,我们将获得原始列表的子集。
nums = [1,2,3,4,5,6,7,8,9]
sub = nums[1:8:2]
print(sub)
输出
[2, 4, 6, 8]
接下来,我们将使用上一节中相同的 info.txt 文档来演示如何使用切片符号来清除文本文件中的行。方法将返回文档中文本行的列表。
提取这些行之后,我们可以使用切片符号来创建一个新的列表,用它来覆盖旧文件。只有第一行文本会保留下来。其他的将从文本文件中清除。
# read the file's contents
read_file = open("info.txt",'r')
lines = read_file.readlines()
read_file.close()
write_file = open("info.txt",'w')
# slice the file's content
lines = lines[:1]
for line in lines:
write_file.write(line)
print(line)
write_file.close()
输出
Guido van Rossum created Python in 1991.
如何从文本文件中删除特定的行
使用一些常见的 Python 函数,我们还可以从文本文件中清除特定的数据行。如果我们事先知道要删除哪些行,这将特别有帮助。在这种情况下,我们可以使用切片符号来检索文件的子集。
通过用文件的数据子集覆盖文件,我们可以删除文本行。下面的例子摘自美国作家兰斯顿·休斯的诗《推迟的梦》。
dream.txt
延期的梦会怎么样?
它会像阳光下的葡萄干一样干枯吗
?
清除文本文件的第一行
为了清除文件的第一行文本,我们需要使用一些 Python 的文件处理方法。首先,我们将使用 readlines ()获取文件的文本数据列表。用 seek ()方法,我们可以手动重新定位文件指针。
其次,我们可以使用截断()的方法来调整文件的大小。第三,我们将向文件中写入一个新的行列表。使用切片符号,可以省略原始文件的第一行。
with open("dream.txt",'r+') as file:
# read the lines
lines = file.readlines()
# move to the top of the file
file.seek(0)
file.truncate()
file.writelines(lines[1:])
with open("dream.txt",'r') as file:
lines = file.readlines()
for line in lines:
print(line)
输出
Does it dry up
Like a raisin in the sun?
从文本文件中清除多行
也可以从文件中删除多行文本。使用切片表示法,我们可以创建任何我们想要的数据子集。使用这种覆盖原始文件的方法,我们可以有效地清除文件中任何不需要的数据。
通过改变切片的开始和结束索引,我们将得到 dream.txt 文件的不同子集。也可以组合分片列表。在创建列表子集时,使用这些工具可以提供很多灵活性。
with open("dream.txt",'r+') as file:
# read the lines
lines = file.readlines()
# move to the top of the file
file.seek(0)
file.truncate()
file.writelines(lines[:3])
with open("dream.txt",'r') as file:
lines = file.readlines()
for line in lines:
print(line)
输出
What happens to a dream deferred?
如何使用字符串清除文本文件
如果我们想从包含某个单词、短语或数字的字符串中删除一行,该怎么办?我们可以用一个 Python if 语句来检查每行的字符串数据。如果我们正在寻找的字符串在该行中,我们可以避免将它包含在输出文件中。
employee.txt
姓名:杰米·詹姆森
年龄:37
职业:文案
起始日期:2019 年 4 月 3 日
在这个例子中,我们需要打开文件三次。首先,我们将打开文件提取其内容。接下来,我们将把数据写入一个新文件,清除我们不想要的行。最后,我们需要打开文件并阅读它,以证明文件得到了正确处理。
data_file = open("employee.txt",'r')
lines = data_file.readlines()
data_file.close()
write_file = open("employee.txt",'w')
for line in lines:
if "Age" not in line:
write_file.write(line)
write_file.close()
read_file = open("employee.txt",'r')
lines = read_file.readlines()
read_file.close()
for line in lines:
print(line)
输出
Name: James Jameson
Occupation: Copywriter
Starting Date: April 3, 2019
摘要
在这篇文章中,我们深入探讨了如何在 Python 中清除文本文件。我们已经看到 Python 语言为完成这项任务提供了许多选项。使用每次安装 Python 时都标配的一些方法和函数,我们能够清除整个文件以及删除文件中的特定行。
虽然像切片符号这样的工具对于清除文本文件非常有用,但是它们在其他领域也很方便。这样,您学习的每一个 Python 新特性都将提高您的整体编码能力。
相关职位
如果你觉得这篇文章很有帮助,并且想学习更多关于 Python 编程的知识,请点击这些链接,阅读我们 Python 初学者团队的更多精彩文章。无论是文件处理还是数据管理,你都会学到在当今快速变化的数字世界中取得成功所需的技能。
如何在 Python 字典中进行注释
原文:https://www.pythonforbeginners.com/comments/how-to-comment-inside-a-python-dictionary
python 中的注释在增加代码的可读性和可维护性方面非常方便。一般来说,我们使用注释来描述函数和类描述,用于文档目的或解释为什么在源代码中编写语句,但可能有这样的情况,我们需要解释为什么我们在字典或列表中包含某些数据。在本文中,我们将看到 python 字典的基本功能,并尝试理解如何在 python 字典中添加注释。
python 字典的工作
在 Python 中,字典是用于以键和值对的形式存储数据的数据结构。python 字典是使用花括号定义的,键和值对在初始化时插入字典中,用冒号":"分隔,或者可以在初始化后使用赋值语句添加。
python 字典中的键值对被称为项目。
初始化字典的最简单方法如下:
website_details={"name":"Pyhton For Beginners",
"domain":"pythonforbeginners.com"
}
print("dictionary is:")
print(website_details)
print("Keys in the dictionary are:")
print(website_details.keys())
print("values in the dictionary are:")
print(website_details.values())
print("itmes in the dictionay are:")
print(website_details.items())
输出:
dictionary is:
{'name': 'Pyhton For Beginners', 'domain': 'pythonforbeginners.com'}
Keys in the dictionary are:
dict_keys(['name', 'domain'])
values in the dictionary are:
dict_values(['Pyhton For Beginners', 'pythonforbeginners.com'])
itmes in the dictionay are:
dict_items([('name', 'Pyhton For Beginners'), ('domain', 'pythonforbeginners.com')])
在上面的例子中,我们可以看到使用花括号定义了一个 python 字典,在字典中指定了键-值对,它们由冒号“:”分隔。
使用dict_name.keys()可以获得字典的键。类似地,字典中的值可以使用dict_name.values()获得,所有的项(键-值对)可以使用dict_name.items()方法获得。
如果我们想在字典中插入新的键值对,我们可以这样做。
website_details={"name":"Pyhton For Beginners",
"domain":"pythonforbeginners.com"
}
#add new item to list
website_details["acronym"]="PFB"
print("dictionary is:")
print(website_details)
print("Keys in the dictionary are:")
print(website_details.keys())
print("values in the dictionary are:")
print(website_details.values())
print("itmes in the dictionay are:")
print(website_details.items())
输出:
dictionary is:
{'name': 'Pyhton For Beginners', 'domain': 'pythonforbeginners.com', 'acronym': 'PFB'}
Keys in the dictionary are:
dict_keys(['name', 'domain', 'acronym'])
values in the dictionary are:
dict_values(['Pyhton For Beginners', 'pythonforbeginners.com', 'PFB'])
itmes in the dictionay are:
dict_items([('name', 'Pyhton For Beginners'), ('domain', 'pythonforbeginners.com'), ('acronym', 'PFB')])
在上面的例子中,我们添加了一个键为“acronym”、值为“PFB”的项目。我们可以像下面的代码片段所示的dict_name[key_name] 一样访问与字典的键相关的值。
website_details={"name":"Pyhton For Beginners",
"domain":"pythonforbeginners.com"
}
#add new item to list
website_details["acronym"]="PFB"
print(website_details["domain"])
输出:
pythonforbeginners.com
在 python 中处理单行注释
通过用符号#初始化注释文本,可以编写一行 python 注释。单行注释在源代码中遇到换行符时终止。
我们可以通过在一个新行上开始来放置单行注释,或者我们可以通过在源代码中的一个语句后放置#符号来放置单行注释,但是应该记住,当在源代码中发现一个新行或换行符时,注释终止。它可以在下面的源代码中可视化。
website_details={"name":"Pyhton For Beginners",
"domain":"pythonforbeginners.com"
}
#This is single line comment from start of line
website_details["acronym"]="PFB"#this is a single line comment after an statement
print(website_details["domain"])
python 中多行注释的处理
从理论上讲,python 中不存在多行注释。但是我们可以在 python 中使用单行注释和三重引号字符串实现多行注释。
我们可以使用单行注释实现多行注释,只要遇到换行符就插入一个#符号。这样,多行注释就被描述为一系列单行注释。
website_details={"name":"Pyhton For Beginners",
"domain":"pythonforbeginners.com"
}
#This is a multi line comment
#implemented using # sign
website_details["acronym"]="PFB"
print(website_details["domain"])
如果我们不把字符串赋给任何变量,我们也可以把它们作为多行注释。当字符串没有被赋给任何变量时,它们会被解释器解析和评估,但不会生成字节码,因为没有地址可以赋给字符串。这将影响字符串作为注释的工作。在这种方法中,可以使用三重引号声明多行注释。这可以看如下。
website_details={"name":"Pyhton For Beginners",
"domain":"pythonforbeginners.com"
}
"""This is a multiline comment
implemented with the help of
triple quoted strings"""
website_details["acronym"]="PFB"
print(website_details["domain"])
在 python 字典中添加单行注释
我们可以像在其他地方一样,使用#符号在 python 字典中添加单行注释。我们只需要将注释后的内容移到新的一行,这样字典的内容就不会被注释掉。
website_details={"name":"Pyhton For Beginners",
#This is a single line comment inserted inside a dictionary
"domain":"pythonforbeginners.com"
}
website_details["acronym"]="PFB"
print(website_details["domain"])
在 python 字典中添加多行注释
我们可以只使用#符号在 python 字典中添加多行注释。理论上,我们只能在 python 字典中添加单行注释,但是我们可以使用连续的单行注释来模拟多行注释。
website_details={"name":"Pyhton For Beginners",
#This is a multiline comment inside a dictionary
#inserted with the help of consecutive single line comments
"domain":"pythonforbeginners.com"
}
website_details["acronym"]="PFB"
print(website_details["domain"])
在 python 字典中使用三重引号字符串作为注释是行不通的,python 解释器会抛出错误。
website_details={"name":"Pyhton For Beginners",
"""This is a multiline comment inside a dictionary
inserted with the help of triple quoted strings and
it will cause error"""
"domain":"pythonforbeginners.com"
}
website_details["acronym"]="PFB"
print(website_details["domain"])
结论
在本文中,我们已经看到了 python 字典的工作方式,以及 python 中的单行注释和多行注释,然后我们尝试实现了在 python 字典中插入单行注释和多行注释的方法。请继续关注更多内容丰富的文章。
如何用 Python 注释掉一段代码
原文:https://www.pythonforbeginners.com/comments/how-to-comment-out-a-block-of-code-in-python
用 Python 编程是令人兴奋的。编写代码并与他人分享会带来令人惊奇的事情。但是在我们的程序成长之前,我们需要确保它们易于阅读。这就是程序员学习如何注释代码块的原因。
为什么让我们的代码可读很重要?简单的答案是,代码被阅读的次数比它被编写的次数多。为了确保我们的代码是可维护的,我们需要让其他人清楚发生了什么。
因此,注释是编写可读代码的必要部分。写注释让我们有机会解释一段代码是做什么的。我们用它们来解释程序中容易混淆或模糊的部分。
为了测试的目的,我们也可以使用注释来删除程序的一部分。通过屏蔽掉一行代码,我们可以防止它被编译。这允许我们测试替代逻辑或排除程序故障。
为什么写评论很重要
随着项目的增长,有必要进行扩展。这意味着更大的代码库和更大的团队。为了让团队正常运作,每个人都需要步调一致。
早期糟糕的选择会导致代码难以维护。如果没有注释来帮助破译代码,对于新开发人员来说,跟上速度可能是一个挑战。你不希望你的同事绞尽脑汁试图弄清楚一些糟糕命名的变量是做什么的。
即使你是一个人工作,以单人模式编写软件,在程序中加入一些注释也是一个好主意。为什么?很有可能,当你一两个月后回到这个项目时,你不会记得所有的事情是如何运作的。对于跨越多个文件的大型程序来说尤其如此。
什么是代码块?
一般来说,代码块指的是组合在一起的多个相似的代码。这可以包括几个陈述以及注释。在 Python 中,代码块位于相同的缩进级别。
示例 1:在 Python 中识别代码块
def print_upper_case(name):
# these statements make up a single block
upper = name.upper()
print(upper)
print_upper_case("taylor") # outside of the block
输出
TAYLOR
在这个例子中,我们已经确定了位于 print_upper_case() 函数下面的代码块。这段代码以一个注释开始,后面是另外两个语句。底部的函数调用在前面提到的代码块之外。
我们真的需要多行注释吗?
有时候注释掉整个代码块会很有用。例如,如果我们需要对一部分代码进行故障诊断,并且我们想看看如果某个块不执行会发生什么。
在这种情况下,注释掉整个代码块会很方便。这样我们就不会丢失已经写好的东西。
此外,虽然保持评论简短是明智的,但有时我们需要不止一行来表达我们的需求。在这种情况下,最好使用块注释。
使用#来注释代码块
用 Python 注释掉一段代码最直接的方法是使用 # 字符。任何以 hashtag 开头的 Python 语句都将被编译器视为注释。
无论是在一行中还是在其他地方,你都可以有无限多的块注释。如果我们需要进行多行注释,这将非常有用。
示例 1:编写消息
def message_writer(msg):
# We may need to do it this way in the future
#new_msg = "Message Writer says: "
#new_msg += msg
#print(new_msg)
print("Message Writer says: " + msg)
message_writer("Lovin' it!")
输出
Lovin' it!
在上面的例子中,我们使用了块注释对编译器暂时隐藏一些 Python 语句。通过在每个语句前添加一个 # ,我们有效地从代码中删除了它。
也许我们有一个开发人员使用的 Python 程序。这是一个系统的设置文件。根据他们的需要,可能需要从程序中删除一些代码行。使用块注释意味着我们可以给这些开发人员几个选项,他们可以通过简单地取消注释这些语句来有效地“打开”。
如何使用文档字符串进行块注释
虽然块注释在技术上允许我们进行多行注释,但是使用它们会很麻烦。如果代码块长于几行,尤其如此。添加和删除标签并不好玩。
幸运的是,有另一种方法可以在 Python 中创建多行注释。我们可以使用 docstrings(文档字符串)来实现这一点。
文档字符串允许我们快速注释掉一段代码。我们可以使用三重引号在 Python 中创建一个 docstring。这个方法得到了 Python 的创造者 Guido Van Rossum 的认可。这里有一个关于使用 docstrings 在 Guido 的 Twitter 页面上发表评论的引用:
Python 提示:可以使用多行字符串作为多行注释。除非用作文档字符串,否则它们不会生成代码!🙂
-Guido Van Rossum
重要的是要记住,文档字符串并不是真正的注释,它们是没有赋给变量的字符串。未赋值的字符串在运行时会被忽略,所以在我们的目的中,它们将起到注释的作用。
然而,docstrings 在 Python 中还有另外一个用途。放在函数或类声明之后,docstring 将作为与该对象相关联的一段文档。在这种情况下,文档字符串作为一种快速生成 API 的方法(应用程序程序接口 I )。
Python 中注释掉代码的替代方法
块注释和文档字符串是在 Python 中创建注释的唯一方法。如果你像我一样,这两种方法都不是你想要的。
幸运的是,我们不必完全依赖 Python 的工具。使用今天的技术,点击鼠标就可以创建多行注释。
使用 IDE 或文本编辑器
除非你是在记事本中写代码,否则你可能会使用一些工具来注释掉一段代码。虽然这个方法对 Python 来说并不明确,但它在现实世界中是一种常见的做法。
使用 IDE(IintegratedDdevelopmentEenvironment),可以一次注释整行代码。在许多情况下,可以从工具栏访问这些特殊功能。这些特性将特定于每个 IDE,因此您需要根据您使用什么软件来编写 Python 代码进行一些研究。
大多数文本编辑器都有一个特性,允许你一次注释掉几行代码。如果您搜索一个专门为开发人员创建的文本编辑器,它可能会有这个特性。
在 Python 中使用多行注释的示例
为了帮助说明何时以及如何使用块注释和文档字符串,我们还包括了几个例子。
def add_square(x,y):
a = x*x
b = y*y
return a + b
print(add_square(2,2))
我们编写的 add_spare() 函数使用了一段代码,需要几行代码来完成所需的计算。这个代码块可以用一行代码重写。我们已经注释掉了旧的行,这样你就可以比较这两种方法。
def add_square(x,y):
#a = x*x
#b = y*y
#return a + b
return (x*x) + (y*y)
print(add_square(2,2))
文档字符串用于定义函数、类或模块。我们可以使用 doc 属性读取文档字符串。
def product(x,y):
'''Returns the product of the given arguments.'''
return x*y
x = 4
y = 3
print("{} x {} = {}".format(x,y,product(x,y)))
print(product.__doc__)
输出
4 x 3 = 12
另一方面,字符串看起来像文档字符串,但它们的工作方式不同。相反,当程序运行时,它们会被忽略。因此,我们可以将它们用作多行注释。
"""
The Fibonacci series is a sequence of numbers where each
term is the sum of the previous two terms.
Starting with 0 and 1, we can compute the nth term in the sequence.
"""
def fib(n):
a,b = 0,1
for i in range(n):
a,b = b,a+b
print(a)
return a
print(fib(10))
用 Python 注释的技巧:
- 保持评论简洁明了。
- 始终保持尊重和乐于助人。
- 记住,最好的代码通过为变量、函数和类使用好的名字来解释自己。
摘要
虽然 Python 确实不像其他编程语言那样支持多行注释,但是使用 # 字符仍然可以创建这些类型的注释。块注释是在 Python 中创建多行注释的标准方式。它们也可以用来注释掉程序中的一段代码。
如果块注释不够,还可以使用 docstrings 创建多行注释。除非以特殊方式使用,否则文档字符串不会生成任何代码。
最后,可以使用现代 IDE 注释掉一段代码。这种方法将取决于您使用的软件,但它通常是一个相当简单的过程。一些程序甚至有热键专门用于注释和取消注释代码块。
相关职位
- 除了语句之外, Python 如何尝试捕捉代码中的错误
- 如何使用一个 Python 字典来存储键值对
如何在 Python 中逐行比较两个文件
原文:https://www.pythonforbeginners.com/basics/how-to-compare-two-files-in-python-line-by-line
本教程研究了在 Python 中比较两个文件的各种方法。我们将讨论读取两个文件并逐行比较它们,以及使用可用的模块来完成这个常见的任务。
在 Python 中有很多方法可以比较两个文件。Python 附带了用于此目的的模块,包括 filecmp 和 difflib 模块。
以下 Python 3 示例对比了确定两个文件是否包含相同数据的各种方法。我们将使用 Python 3 内置的函数和模块,因此不需要下载额外的包。
逐行比较两个文本文件
我们可以使用 open ()函数读取文件中包含的数据来比较两个文本文件。open()函数将在本地目录中查找一个文件,并尝试读取它。
对于这个例子,我们将比较两个包含电子邮件数据的文件。我们被告知,这两份邮件列表可能并不相同。我们将让 Python 为我们检查文件。使用 readlines ()方法,可以从文本文件中提取行。
emails_A.txt
【邮件保护】
【邮件保护】
【邮件保护】
【邮件保护】
【邮件保护】
emails_B.txt
【邮件保护】
【邮件保护】
【邮件保护】
【邮件保护】
【邮件保护】
一旦数据被提取,一个 for 循环 用于逐行比较文件。如果这些行不匹配,用户会收到一条消息,告诉他们不匹配发生在哪里。我们将包括数据本身,这样用户可以很容易地跟踪不同的行。
示例:使用 Python 比较电子邮件列表
file1 = open("emails_A.txt",'r')
file2 = open("emails_B.txt",'r')
file1_lines = file1.readlines()
file2_lines = file2.readlines()
for i in range(len(file1_lines)):
if file1_lines[i] != file2_lines[i]:
print("Line " + str(i+1) + " doesn't match.")
print("------------------------")
print("File1: " + file1_lines[i])
print("File2: " + file2_lines[i])
file1.close()
file2.close()
输出
Line 1 doesn't match.
------------------------
File1: [[email protected]](/cdn-cgi/l/email-protection)
File2: [[email protected]](/cdn-cgi/l/email-protection)
Line 3 doesn't match.
------------------------
File1: [[email protected]](/cdn-cgi/l/email-protection)
File2: [[email protected]](/cdn-cgi/l/email-protection)
Line 4 doesn't match.
------------------------
File1: [[email protected]](/cdn-cgi/l/email-protection)
File2: [[email protected]](/cdn-cgi/l/email-protection)
使用 filecmp 模块比较文件
filecmp 模块包括用于在 Python 中处理文件的函数。具体来说,这个模块用于比较两个或多个文件之间的数据。我们可以使用 filecmp.cmp ()方法来实现这一点。如果文件匹配,这个方法将返回真,否则返回假。
这个例子使用了三个文件。第一个和第三个是一样的,而第二个略有不同。我们将使用 filecmp.cmp()方法通过 Python 来比较这些文件。
标点 1.txt
吃你的晚餐。
我要感谢我的父母、珍妮特和上帝。
对不起我关心你。她真的很喜欢烹饪、她的家庭和她的猫。
标点符号 2.txt
吃。你是晚餐!我要感谢我的父母、珍妮特和上帝。
对不起。我关心你。她真的很喜欢烹饪她的家人和她的猫。
标点 3.txt
吃你的晚餐。
我要感谢我的父母、珍妮特和上帝。
对不起我关心你。她真的很喜欢烹饪、她的家庭和她的猫。
在使用 filecmp 模块之前,我们需要导入它。我们还需要导入 os 模块,这将允许我们使用目录中的路径加载文件。在本例中,使用了一个自定义函数来完成比较。
在我们比较文件之后,我们可以看到数据是否匹配,最后,我们将提醒用户结果。
示例:用 filecmp.cmp() 比较两个文件
import filecmp
import os
# notice the two backslashes
file1 = "C:\\Users\jpett\\Desktop\\PythonForBeginners\\2Files\\punctuation1.txt"
file2 = "C:\\Users\jpett\\Desktop\\PythonForBeginners\\2Files\\punctuation2.txt"
file3 = "C:\\Users\jpett\\Desktop\\PythonForBeginners\\2Files\\punctuation3.txt"
def compare_files(file1,file2):
compare = filecmp.cmp(file1,file2)
if compare == True:
print("The files are the same.")
else:
print("The files are different.")
compare_files(file1,file2)
compare_files(file1,file3)
输出
The files are different.
The files are the same.
使用 difflib 模块比较两个文件
difflib 模块对于比较文本和找出它们之间的差异很有用。这个 Python 3 模块预打包了该语言。它包含许多有用的功能来比较正文。
首先,我们将使用 unified_diff ()函数来查明两个数据文件之间的不匹配。这些文件包含虚构学生的信息,包括他们的姓名和平均绩点。
其次,我们将比较这些学生记录,并检查学生的成绩从 2019 年到 2020 年是如何变化的。我们可以使用 unified_diff()函数来实现这一点。下面的例子使用带有语句的来读取文件数据。通过使用 Python with 语句,我们可以安全地打开和读取文件。
student_gpa_2019.txt
切尔西-沃克 3.3
卡洛琳-贝内特 2.8
加里-霍姆斯 3.7
拉斐尔-罗杰斯 3.6
帕特里克-尼尔森 2.1
student_gpa_2020.txt
切尔西-沃克 3.6
卡洛琳-贝内特 2.7
加里-霍姆斯 3.7
拉斐尔-罗杰斯 3.7
帕特里克-尼尔森 2.1
示例:比较学生的 GPA
import difflib
with open("student_gpa_2019.txt",'r') as file1:
file1_contents = file1.readlines()
with open("student_gpa_2020.txt",'r') as file2:
file2_contents = file2.readlines()
diff = difflib.unified_diff(
file1_contents, file2_contents, fromfile="file1.txt",
tofile="file2.txt", lineterm='')
for line in diff:
print(line)
输出
--- file1.txt
+++ file2.txt
@@ -1,5 +1,5 @@
-Chelsea Walker 3.3
-Caroline Bennett 2.8
+Chelsea Walker 3.6
+Caroline Bennett 2.7
Garry Holmes 3.7
-Rafael Rogers 3.6
+Rafael Rogers 3.7
Patrick Nelson 2.1
查看输出,我们可以看到 difflib 模块不仅仅是逐行比较文本文件。unified_diff()函数还提供了一些关于所发现的差异的上下文。
比较两个。Python 中的 csv 文件逐行
逗号分隔值文件用于在程序之间交换数据。Python 也提供了处理这些文件的工具。通过使用 csv 模块,我们可以快速访问 csv 文件中的数据。
使用 csv 模块,我们将比较两个数据文件并识别不匹配的行。这些文件包含员工记录,包括每个员工的名字、姓氏和电子邮件。这些数据是随机生成的,但我们会假装我们的员工迫切需要我们来完成比较。
employeesA.csv
【名】【姓】【电子邮件】
【大卫】【克劳福德】【电子邮件保护】
【莎拉】【佩恩】【电子邮件保护】
【罗伯特】【库珀】【电子邮件保护】
【艾达】【亚历山大】【电子邮件保护】
【瓦莱里娅】【道格拉斯】
employees sb . CSV
【名】【姓】【电子邮件】
【安德鲁】【克劳福德】【电子邮件保护】
【莎拉】【佩恩】【电子邮件保护】
【罗伯特】【库珀】【电子邮件保护】
【阿加塔】【安德森】【电子邮件保护】
【麦莉】【福尔摩斯】
一旦我们有了雇员数据,我们就可以使用 reader()函数读取它。包含在 csv 模块中的 reader()函数可以解释 csv 数据。收集完数据后,我们可以使用 Python 将数据转换成列表。
最后,使用 for 循环,我们将比较两个列表的元素。每个元素将保存雇员数据文件中的一行。这样,我们可以遍历列表并发现哪些行不相同。
Python 程序将逐行比较这些文件。因此,我们可以识别雇员数据文件之间的所有差异。
示例:使用 csv 模块比较员工数据文件
import csv
file1 = open("employeesA.csv",'r')
file2 = open("employeesB.csv",'r')
data_read1= csv.reader(file1)
data_read2 = csv.reader(file2)
# convert the data to a list
data1 = [data for data in data_read1]
data2 = [data for data in data_read2]
for i in range(len(data1)):
if data1[i] != data2[i]:
print("Line " + str(i) + " is a mismatch.")
print(f"{data1[i]} doesn't match {data2[i]}")
file1.close()
file2.close()
输出
Line 1 is a mismatch.
['David', 'Crawford', '[[email protected]](/cdn-cgi/l/email-protection)'] doesn't match ['Andrew', 'Crawford', '[[email protected]](/cdn-cgi/l/email-protection)']
Line 4 is a mismatch.
['Aida', 'Alexander', '[[email protected]](/cdn-cgi/l/email-protection)'] doesn't match ['Agata', 'Anderson', '[[email protected]](/cdn-cgi/l/email-protection)']
Line 5 is a mismatch.
['Valeria', 'Douglas', '[[email protected]](/cdn-cgi/l/email-protection)'] doesn't match ['Miley', 'Holmes', '[[email protected]](/cdn-cgi/l/email-protection)']
最后
Python 提供了许多比较两个文本文件的工具,包括 csv 文件。在这篇文章中,我们讨论了 Python 3 中的许多函数和模块。此外,我们已经看到了如何使用它们在 Python 中逐行比较文件。
通过发现新的模块,我们可以编写使我们的生活更容易的程序。我们日常使用的许多程序和 web 应用程序都是由 Python 驱动的。
相关职位
如何在 Python 中创建迭代器
原文:https://www.pythonforbeginners.com/basics/how-to-create-an-iterator-in-python
迭代器用于以顺序方式访问可迭代对象的元素。我们可以为任何容器对象创建一个迭代器,比如一个 python 字典、列表、元组或集合。在本文中,我们将讨论如何在 python 中创建迭代器。我们还将学习如何通过重写内置方法来创建自定义迭代器。
使用内置方法创建迭代器
我们可以使用 iter()函数和 next()方法创建一个迭代器。iter()函数接受一个容器对象,比如 list、tuple 或 set,并返回一个迭代器,通过它我们可以访问容器对象的元素。
要使用 iter()函数为任何容器对象创建迭代器,我们只需将对象传递给 iter()函数。该函数创建一个迭代器并返回对它的引用。我们可以使用 iter()函数创建一个迭代器,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
myIter = iter(myList)
print("The list is:", myList)
print("The iterator is:", myIter)
输出:
The list is: [1, 2, 3, 4, 5, 6, 7]
The iterator is: <list_iterator object at 0x7f73fed18070>
在输出中,您可以看到在执行 iter()函数时创建了一个 list_iterator 对象。
如何从迭代器中访问元素?
要使用序列中的迭代器访问容器对象的元素,我们可以使用如下的 for 循环。
myList = [1, 2, 3, 4, 5, 6, 7]
myIter = iter(myList)
print("The list is:", myList)
print("The elements in the iterator are:")
for i in myIter:
print(i)
输出:
The list is: [1, 2, 3, 4, 5, 6, 7]
The elements in the iterator are:
1
2
3
4
5
6
7
如果需要逐个访问元素,可以使用 next()函数或 __next()方法。
为了使用 next()函数遍历迭代器,我们将迭代器作为输入参数传递给函数。它返回迭代器中的下一个元素。next()函数还会记住迭代器上次遍历的索引。当再次调用它时,它返回尚未遍历的下一个元素。这可以在下面的例子中观察到。
myList = [1, 2, 3, 4, 5, 6, 7]
myIter = iter(myList)
print("The list is:", myList)
print("The elements in the iterator are:")
element = next(myIter)
print(element)
element = next(myIter)
print(element)
element = next(myIter)
print(element)
element = next(myIter)
print(element)
element = next(myIter)
print(element)
element = next(myIter)
print(element)
element = next(myIter)
print(element)
输出:
The list is: [1, 2, 3, 4, 5, 6, 7]
The elements in the iterator are:
1
2
3
4
5
6
7
Process finished with exit code 0
next()方法的工作方式与 next()函数类似。每当在迭代器上调用 next()方法时,它都会返回尚未遍历的下一个元素。
myList = [1, 2, 3, 4, 5, 6, 7]
myIter = iter(myList)
print("The list is:", myList)
print("The elements in the iterator are:")
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
输出:
The list is: [1, 2, 3, 4, 5, 6, 7]
The elements in the iterator are:
1
2
3
4
5
6
7
Process finished with exit code 0
当没有元素可供遍历,并且我们使用 next()函数或 next()方法时,它会引发 StopIteration 异常。
myList = [1, 2, 3, 4, 5, 6, 7]
myIter = iter(myList)
print("The list is:", myList)
print("The elements in the iterator are:")
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 19, in <module>
element = myIter.__next__()
StopIteration
建议在 python try except 块中使用这些函数来避免异常。
如何在 Python 中创建自定义迭代器
要创建自定义迭代器,我们可以覆盖设置为 default 的 iter()和 next()方法。我们将通过下面的例子来理解如何创建一个自定义迭代器。
假设您想要创建一个迭代器,当我们使用迭代器遍历对象时,它返回列表或元组中每个元素的平方。为此,我们将重写 iter()方法和 next()方法。
迭代器的构造函数将接受列表或元组以及其中的元素总数。然后它将初始化迭代器类。因为我们需要跟踪被遍历的最后一个元素,我们将初始化一个索引字段,并将其设置为 0。
class SquareIterator:
def __init__(self, data, noOfElements):
self.data = data
self.noOfElements = noOfElements
self.count = 0
方法的作用是初始化一个迭代器。iter()方法实现如下。
class SquareIterator:
def __init__(self, data, noOfElements):
self.data = data
self.noOfElements = noOfElements
self.count = 0
def __iter__(self):
return self
在重写 iter()方法之后,我们将重写 next()方法。next()方法用于遍历尚未遍历的下一个元素。这里,我们需要返回下一个元素的平方。
因为我们已经在 iter()方法中将索引初始化为-1,所以我们将首先递增索引。之后,我们将返回指定索引处元素的平方。每次调用 next()方法时,索引都会递增,指定索引处的元素的平方将作为输出给出。当遍历的元素数量等于列表或元组中元素的总数时,我们将引发 StopIteration 异常。它将停止迭代。next()方法可以定义如下。
class SquareIterator:
def __init__(self, data, noOfElements):
self.data = data
self.noOfElements = noOfElements
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count < self.noOfElements:
square = self.data[self.count] ** 2
self.count = self.count + 1
return square
else:
raise StopIteration
创建迭代器的整个程序如下。
class SquareIterator:
def __init__(self, data, noOfElements):
self.data = data
self.noOfElements = noOfElements
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count < self.noOfElements:
square = self.data[self.count] ** 2
self.count = self.count + 1
return square
else:
raise StopIteration
myList = [1, 2, 3, 4, 5, 6, 7]
myIter = SquareIterator(myList, 7)
print("The list is:", myList)
print("The elements in the iterator are:")
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
element = myIter.__next__()
print(element)
输出:
The list is: [1, 2, 3, 4, 5, 6, 7]
The elements in the iterator are:
1
4
9
16
25
36
49
Process finished with exit code 0
结论
在本文中,我们研究了在 Python 中创建迭代器的两种方法。在遍历容器对象时,可以使用自定义迭代器对容器对象的元素执行不同的操作。建议实现一些程序来创建迭代器,以便更好地理解这个主题。
如何在 Python 中创建多行注释
原文:https://www.pythonforbeginners.com/comments/how-to-create-multiline-comments-in-python
注释通过提供有关代码的适当信息,用于增强源代码的可读性和可理解性。注释不是由解释器或编译器执行的,它们在代码中使用只是为了帮助程序员。在本文中,我们将了解如何在 python 中创建多行注释。
python 中的多行注释是什么?
正如我们在名字中看到的,多行注释是扩展到多行的 python 注释,即多行注释是那些在源代码中扩展到两行或更多行的注释。从理论上讲,python 中没有多行注释的语法,但是我们可以使用单行注释或三重引号字符串实现多行注释。我们将逐一查看实现多行注释的两种方法。
如何使用# symbol 在 python 中创建多行注释?
正如我们所知,python 中单行注释是通过在注释前添加#符号来实现的,只要出现换行符,注释就会终止,我们可以在多行注释的每一行的开头添加#符号。这样,我们可以使用单行注释实现多行注释。这可以看如下。示例中的函数将一个数字及其平方作为键值对添加到一个 python 字典中。
#This is a multiline comment in python
#and expands to more than one line
def add_square_to_dict(x,mydict):
#This is an example of block of code where the block consists of an entire function
a=x*x
mydict[str(x)]=a
return mydict
在 python 中,我们可以在源代码中的任何语句后开始一行注释。类似地,当我们使用# symbol 实现多行注释时,我们可以在代码中的任何语句后开始多行注释。
#This is a multiline comment in python
#and expands to more than one line
print("Pythonforbeginners.com") #This is also a python comment
#and it also expands to more than one line.
如何在 python 中使用多行字符串创建多行注释?
要在 python 中使用多行字符串作为多行注释,我们可以使用多行字符串,而不用将它赋给任何变量。这样,当解释器执行代码时,不会为未赋值的字符串生成字节码,因为没有地址可以分配给它。这样,多行字符串将充当多行注释。这可以看如下。
"""This is
a
multiline comment in python
which expands to many lines"""
print("PythonforBeginners.com")
当我们用#符号实现多行注释时,我们可以在 python 中的语句后开始多行注释。但是如果我们使用多行字符串来实现多行注释,我们就不能在任何语句后开始多行注释。如果这样做,就会导致错误。这可以看如下。
#This is a multiline comment in python
#and expands to more than one line
"""This is
a
multiline comment in python
which expands to many lines"""
print("Pythonforbeginners.com") """This is not
a
multiline comment in python
and will cause syntax error"""
当我们使用#符号实现注释时,我们不必关心缩进,但是当我们使用多行字符串作为注释时,我们必须遵循正确的缩进,否则将会出现错误。这可以看如下。
#This is a multiline comment in python
#and expands to more than one line wthout caring for indentation
"""This is
a
multiline comment in python
which expands to many lines and should follow indentation"""
print("Pythonforbeginners.com")
结论
在本文中,我们看到了用 python 创建多行注释的各种方法。我们还看到了如何使用多行注释,以便它们不会在程序中导致错误。请继续关注更多内容丰富的文章。
如何删除文件中的特定行
原文:https://www.pythonforbeginners.com/files/how-to-delete-a-specific-line-in-a-file
因为 Python 没有提供删除文件中特定行的直接方法,所以有必要找到我们自己的方法。
在本指南中,我们将介绍几种使用 Python 从文本文件中移除行的方法。我们将看到如何根据行在文档中的位置删除行,以及如何删除与字符串匹配的内容。
我们还将介绍使用定制逻辑解决更具挑战性的问题的例子。不管我们是处理简单的文本文件,还是更复杂的逗号分隔文件(CSV),这些技术都将帮助您管理您的数据。
我们可以使用 Python 以一种内存高效的方式处理大文件和小文件。
使用数字删除一行
在我们的第一个例子中,我们将根据一行在文件中的位置来删除它。从保存在我们计算机上的随机生成的姓名列表开始,我们将使用 Python 根据姓名在列表中出现的顺序从列表中删除一个姓名。
该文件名为 names.txt ,保存在与我们的 python 文件相同的目录中。我们的目标是删除文件中的第 7 行。
在 Python 中,我们可以使用带有语句的来安全地打开文件。打开文件后,我们将使用 readlines() 方法来检索包含文件内容的列表。
名单看完就这么多。接下来,我们将使用另一个带有语句的再次打开文件,这次是在写模式下。
使用 for 循环遍历文件中的行,我们还利用一个变量来跟踪当前的行号。当我们到达我们想要删除的行时,一个 if 语句确保我们跳过该行。
让我们再复习一遍这些步骤:
- 以读取模式打开文件
- 阅读文件内容
- 以写模式打开文件
- 使用 for 循环读取每一行并将其写入文件
- 当我们到达我们想要删除的行时,跳过它
因为我们使用带有语句的 Python 来处理文件,所以在我们完成后没有必要关闭它。Python 为我们处理了这一点。
names.txt
示例 1:根据指定的行号删除一行
def remove_line(fileName,lineToSkip):
""" Removes a given line from a file """
with open(fileName,'r') as read_file:
lines = read_file.readlines()
currentLine = 1
with open(fileName,'w') as write_file:
for line in lines:
if currentLine == lineToSkip:
pass
else:
write_file.write(line)
currentLine += 1
# call the function, passing the file and line to skip
remove_line("names.txt",7)
通过将我们的逻辑包装在一个函数中,我们可以通过调用 remove_lines()并传递文件名和我们想要删除的行号来轻松地从文件中删除一行。
如果我们计划不止一次地使用一个 Python 代码块,将它包装在一个函数中是一个好主意。这样做会节省我们的时间和精力。
通过匹配内容删除一行
我们已经看到了如何根据行的位置从文件中删除内容。现在我们来看看如何删除匹配给定字符串的行。
我们有一本童谣目录,但有人对我们搞了点恶作剧。具有讽刺意味的是,他们在我们的文件中添加了“此行不属于”这一行!
没必要惊慌。我们可以使用 Python 轻松地消除这种危害。
在我们的 Python 代码中,我们将首先读取名为 itsy_bitsy.txt 的文件,并将其内容存储在名为 lines 的变量中。
就像前面的例子一样,我们将使用 Python 和语句来打开文件。为了找到匹配的行,我们需要删除 readlines() 加在每个字符串末尾的换行符。
我们可以使用 strip() 函数删除换行符。这是一个内置函数,可以删除字符串开头或结尾的字符。
当找到匹配的内容时,我们将使用 if 语句传递它,有效地将它从旧文件中删除。
小小的蜘蛛爬上了水龙卷。
大雨
降临,把蜘蛛冲走了。太阳出来了,这条线不属于这里,它擦干了所有的雨水,小蜘蛛又爬上了壶嘴。
示例 2:匹配内容并将其从文件中移除
with open("itsy_bitsy.txt", 'r') as file:
lines = file.readlines()
# delete matching content
content = "This line doesn't belong"
with open("itsy_bitsy.txt", 'w') as file:
for line in lines:
# readlines() includes a newline character
if line.strip("\n") != content:
file.write(line)
使用自定义逻辑删除 Python 中的一行
在处理文件数据时,我们经常需要定制的解决方案来满足我们的需求。在下面的例子中,我们将探索使用自定义逻辑来解决各种数据问题。
通过定制我们的解决方案,有可能解决更困难的问题。例如,如果我们想从文件中删除一行,但只知道它的一部分,该怎么办?
即使我们只知道一个单词,我们也可以使用 Python 找到需要删除的行。通过利用 Python 的内置方法,我们将看到如何用 Python 代码解决定制挑战。
删除带有特定字符串的行
在下一个练习中,我们将了解如何删除包含字符串一部分的行。基于从前面的例子中获得的知识,可以删除包含给定子串的行。
在 Python 中, find() 方法可用于在字符串中搜索子串。如果字符串包含子字符串,函数将返回表示其位置的索引。否则,该方法返回-1。
在一个名为 statements.txt 的文本文件中,我们有一个随机生成的句子列表。我们需要删除包含给定子串的任何句子。
通过使用 find(),我们将知道一行是否包含我们正在寻找的字符串。如果有,我们会从文件中删除。
下面是使用 find(): 的语法
mystring.find(substring)
statement . txt
他没有注意到关于香蕉的警告。我的朋友带着苹果去了市场。
她买了一个种植桃子的农场。山那边有一个可爱的葡萄园。她非常喜欢她的新车。
示例 3:删除包含给定字符串的行
# remove a line containing a string
with open("statements.txt",'r') as file:
lines = file.readlines()
with open("statements.txt",'w') as file:
for line in lines:
# find() returns -1 if no match is found
if line.find("nuts") != -1:
pass
else:
file.write(line)
删除文件中最短的一行
我们再来看看 statement.txt 。已经做了一些改变。
statement . txt
他没有理会关于香蕉的警告。我的朋友带着苹果去市场。她买了一个种植桃子的农场。他声称看到了不明飞行物。山那边有一个可爱的葡萄园。除了椰子,这个岛上几乎没有什么可吃的。
我们增加了一些新的台词。这一次,我们需要删除文档中最短的一行。我们可以通过使用 len() 方法来找到每一行的长度。
通过比较线路的长度,可以找到最短的线路。随后,我们可以使用一个带有语句的打开并从文件中删除该行。
示例 4:使用 len()方法删除文件中最短的一行
# remove the shortest line from statements.txt
with open("statements.txt",'r') as read_file:
lines = read_file.readlines()
shortest = 1000 # used to compare line length
lineToDelete = "" # the line we want to remove
for line in lines:
if len(line) < shortest:
shortest = len(line)
lineToDelete = line
with open("statements.txt",'w') as write_file:
for line in lines:
if line == lineToDelete:
pass
else:
write_file.write(line)
摘要
在这篇文章中,我们介绍了几种在 Python 中从文件中删除行的方法。我们看到,我们可以使用 for 循环根据行在文件中的位置删除行。
我们还可以通过比较字符串来删除匹配内容的文件,或者使用 == 操作符,或者使用 find() 方法。
这些只是在 Python 中从文件中删除行的一些方法。
相关职位
如果您想了解更多关于使用 Python 处理字符串和文件数据的信息,请点击下面的链接。
- 用 Python 字符串连接连接字符串
- 如何使用 Python 字典进行更好的数据管理
- 使用 Python 列表理解来简化你的代码
如何在 Python 中检测按键
原文:https://www.pythonforbeginners.com/basics/how-to-detect-keypress-in-python
在创建运行图形用户界面的程序时,我们需要检测用户是否按了几次键。在本文中,我们将看到如何在 python 中检测按键。
使用 Python 中的键盘模块检测按键
为了在 python 中检测按键,我们可以使用键盘模块。它可以在 Windows 和 Linux 操作系统上运行,并且支持所有的热键。您可以使用 PIP 在机器上安装键盘模块,如下所示。
pip install keyboard
为了检测按键,我们将使用键盘模块中定义的is_pressed()函数。is_pressed()接受一个字符作为输入,如果在键盘上按下具有相同字符的键,则返回True。因此,我们可以使用带有 while 循环的is_pressed() 函数来检测 python 中的按键,如下例所示。
import keyboard
while True:
if keyboard.is_pressed("a"):
print("You pressed 'a'.")
break
输出:
aYou pressed 'a'.
这里,我们已经执行了 while 循环,直到用户按下键“a”。按下其他键时,is_pressed()函数返回False,while 循环继续执行。一旦用户按下“a”,,if 块内的条件变为真,break 语句被执行。因此 while 循环终止。
代替 is_pressed()函数,我们可以使用read_key()函数来检测按键。read_key()函数返回用户按下的键。我们可以使用带有 while 循环的read_key()函数来检查用户是否按下了特定的键,如下所示。
import keyboard
while True:
if keyboard.read_key() == "a":
print("You pressed 'a'.")
break
输出:
You pressed 'a'.
我们还可以使用键盘模块中定义的wait()函数来检测按键。wait()函数接受一个字符作为输入。在执行时,它会一直等待,直到用户按下作为输入参数传递给函数的键。一旦用户按下右键,该功能将停止执行。您可以在下面的示例中观察到这一点。
import keyboard
keyboard.wait("a")
print("You pressed 'a'.")
输出:
You pressed 'a'.
结论
在本文中,我们讨论了使用键盘模块在 python 中检测按键的不同方法。要了解更多关于输入的内容,你可以阅读这篇关于用 python 从键盘获取用户输入的文章。您可能也会喜欢这篇关于 python 中的字符串连接的文章。
如何用 Python 从. txt 文件中提取日期
原文:https://www.pythonforbeginners.com/files/how-to-extract-a-date-from-a-txt-file-in-python
在本教程中,我们将研究使用 Python 编程从. txt 文件中提取日期的不同方法。Python 是一种通用的语言——您将会发现——这个问题有许多解决方案。
首先,我们将看看如何使用正则表达式模式在文本文件中搜索符合预定义格式的日期。我们将学习使用 re 库和创建我们自己的正则表达式搜索。
我们还将检查 datetime 对象,并使用它们将字符串转换成数据模型。最后,我们将看到 datefinder 模块如何简化在文本文件中搜索未格式化日期的过程,就像我们在自然语言内容中可能会发现的那样。
使用正则表达式从. txt 文件中提取日期
日期有许多不同的格式。有时人们写月/日/年。其他日期可能包括一天中的时间或一周中的某一天(2021 年 7 月 8 日星期三晚上 8:00)。
在我们从文本文件中提取日期之前,如何格式化日期是一个需要考虑的因素。
例如,如果日期遵循月/日/年格式,我们可以使用正则表达式模式找到它。使用正则表达式,或者简称为 regex ,我们可以通过将字符串与预定义的模式进行匹配来搜索文本。
正则表达式的美妙之处在于我们可以使用特殊字符来创建强大的搜索模式。例如,我们可以设计一个模式,在下面的正文中查找所有格式化的日期。
minutes . txt
2021 年 10 月 14 日-会见客户。
2021 年 7 月 1 日——讨论营销策略。
2021 年 12 月 23 日——采访新的团队领导。
2018 年 1 月 28 日–变更域名提供商。
2017 年 6 月 11 日–讨论搬到新办公室。
示例:使用正则表达式查找格式化日期
import re
# open the text file and read the data
file = open("minutes.txt",'r')
text = file.read()
# match a regex pattern for formatted dates
matches = re.findall(r'(\d+/\d+/\d+)',text)
print(matches)
输出
[’10/14/2021′, ’07/01/2021′, ’12/23/2021′, ’01/28/2018′, ’06/11/2017′]
这里的 regex 模式使用特殊字符来定义我们想要从文本文件中提取的字符串。字符 d 和 + 告诉 regex 我们正在文本中寻找多个数字。
我们还可以使用 regex 来查找以不同方式格式化的日期。通过改变 regex 模式,我们可以找到使用正斜杠( * )或破折号(–*)作为分隔符的日期。
这是因为正则表达式允许在搜索模式中使用可选字符。我们可以指定任何一个字符——正斜杠或破折号——都是可接受的匹配。
第一台 Apple II 于 1977 年 7 月 10 日售出。最后一批 Apple II
型号于 1994 年 10 月 15 日停产。
示例:用正则表达式模式匹配日期
import re
# open a text file
f = open("apple2.txt", 'r')
# extract the file's content
content = f.read()
# a regular expression pattern to match dates
pattern = "\d{2}[/-]\d{2}[/-]\d{4}"
# find all the strings that match the pattern
dates = re.findall(pattern, content)
for date in dates:
print(date)
f.close()
输出
1977 年 10 月 7 日
1994 年 10 月 15 日
研究 regex 的全部潜力超出了本教程的范围。尝试使用以下一些特殊字符,以了解有关使用正则表达式模式从. txt 文件中提取日期或其他信息的更多信息。
正则表达式中的特殊字符
- \ s–空格字符
- \ S–除空格字符以外的任何字符
- \ d–0 到 9 之间的任何数字
- \ D–以及除数字以外的任何字符
- \ w–任何字符或数字的单词[a-zA-Z0-9]
- \ W–任何非单词字符
从. txt 文件中提取日期时间对象
在 Python 中,我们可以使用 datetime 库来处理日期和时间。datetime 库预装了 Python,所以不需要安装它。
通过使用 datetime 对象,我们可以更好地控制从文本文件中读取的字符串数据。例如,我们可以使用 datetime 对象来获取计算机当前日期和时间的副本。
import datetime
now = datetime.datetime.now()
print(now)
输出
2021-07-04 20:15:49.185380
在下面的例子中,我们将从一家公司提取一个日期。提及预定会议的 txt 文件。我们的雇主需要我们扫描一组这样的文件的日期。稍后,我们计划将收集到的信息添加到 SQLite 数据库中。
我们将从定义一个匹配日期格式的正则表达式模式开始。一旦找到匹配,我们将使用它从字符串数据创建一个日期时间对象。
schedule.txt
这个项目下个月开始。丹尼斯计划于 2021 年 7 月 10 日在大使馆的会议室开会。
示例:从文件数据创建日期时间对象
import re
from datetime import datetime
# open the data file
file = open("schedule.txt", 'r')
text = file.read()
match = re.search(r'\d+-\d+-\d{4}', text)
# create a new datetime object from the regex match
date = datetime.strptime(match.group(), '%d-%m-%Y').date()
print(f"The date of the meeting is on {date}.")
file.close()
输出
The date of the meeting is on 2021-07-10.
用 Datefinder 模块从文本文件中提取日期
Python datefinder 模块可以在文本主体中定位日期。使用 find_dates ()方法,可以在文本数据中搜索许多不同类型的日期。Datefinder 将以 datetime 对象的形式返回它找到的任何日期。
与我们在本指南中讨论的其他包不同,Python 没有提供 datefinder。安装 datefinder 模块最简单的方法是在命令提示符下使用 pip 。
pip install datefinder
安装了 datefinder 后,我们就可以打开文件并提取数据了。对于这个例子,我们将使用一个介绍虚构公司项目的文本文档。使用 datefinder,我们将从。txt 文件,并打印它们的 datimeobject 副本。
请随意将文件保存在本地,然后继续操作。
project_timeline.txt
项目胡椒
所有团队成员必须在 2021 年 1 月 4 日之前阅读项目总结。
胡椒计划的第一次会议于 2021 年 1 月 15 日召开
上午九点。请在那之前抽出时间阅读下面的链接。
创建于 08-12-2021 下午 05:00
此项目文件包含多种格式的日期。日期用破折号和正斜线书写。更糟糕的是,一月份被写出来。如何用 Python 找到所有这些日期?
示例:使用 datefinder 从文件数据中提取日期
import datefinder
# open the project schedule
file = open("project_timeline.txt",'r')
content = file.read()
# datefinder will find the dates for us
matches = list(datefinder.find_dates(content))
if len(matches) > 0:
for date in matches:
print(date)
else:
print("Found no dates.")
file.close()
产量
2021-01-04 00:00:00
2021-01-15 09:00:00
2021-08-12 17:00:00
从输出中可以看到,datefinder 能够在文本中找到各种日期格式。该软件包不仅能够识别月份名称,而且如果包含在文本中,它还能识别一天中的时间。
在另一个例子中,我们将使用 datefinder 包从一个. txt 文件中提取一个日期,该文件包含一位流行歌手即将到来的巡演的日期。
tour _ dates . txt
2021 年 7 月 25 日星期六下午 07:00 加利福尼亚州英格尔伍德
2021 年 7 月 26 日星期日下午 7:00 加利福尼亚州英格尔伍德
2021 年 9 月 30 日下午 7:30 马萨诸塞州福克斯堡
示例:使用 datefinder 从. txt 文件中提取游览日期和时间
import datefinder
# open the project schedule
file = open("tour_dates.txt",'r')
content = file.read()
# datefinder will find the dates for us
matches = list(datefinder.find_dates(content))
if len(matches) > 0:
print("TOUR DATES AND TIMES")
print("--------------------")
for date in matches:
# use f string to format the text
print(f"{date.date()} {date.time()}")
else:
print("Found no dates.")
file.close()
输出
游览日期和时间
————————
2021-07-25 19:00:00
2021-07-26 19:00:00
2021-09-30 19:30:00
从示例中可以看出,datefinder 可以找到许多不同类型的日期和时间。如果您要查找的日期没有特定的格式,这很有用,自然语言数据中经常会出现这种情况。
摘要
在这篇文章中,我们介绍了几种从. txt 文件中提取日期或时间的方法。我们已经看到了正则表达式在字符串数据中查找匹配的强大功能,以及如何将这些数据转换成 Python datetime 对象。
最后,如果你的文本文件中的日期没有指定的格式——大多数包含自然语言内容的文件都是这种情况——试试 datefinder 模块。有了这个 Python 包,就可以从一个事先没有方便格式化的文本文件中提取日期和时间。
相关职位
如果你喜欢本教程,并渴望了解更多关于 Python 的知识——我们真诚地希望你是这样——请点击这些链接,获取更多 Python 初学者指南。
- 如何使用 Python 串联来连接字符串
- 使用 Python try catch 来减少错误并防止崩溃
如何在 Python 中获得一个列表作为用户输入
原文:https://www.pythonforbeginners.com/basics/how-to-get-a-list-as-user-input-in-python
我们可以使用 input()函数从用户那里获取一个值作为输入。如果我们必须得到一个值列表作为输入呢?在本文中,我们将讨论在 Python 中获取列表作为用户输入的两种方法。
使用 For 循环获取一个列表作为用户输入
我们可以使用 python 中的 for 循环获得一个值列表。为此,我们可以首先创建一个空列表和一个计数变量。之后,我们将询问用户列表中值的总数。获得值的总数后,我们可以使用 for 循环运行 input()函数 count 次,并使用 append()方法将输入添加到列表中,如下所示。
input_count = int(input("Input the Total number of elements in the list:"))
input_list = list()
for i in range(input_count):
input_value = input("Enter value {}:".format(i + 1))
input_list.append(input_value)
print("The list given as input by the user is :", input_list)
输出:
Input the Total number of elements in the list:5
Enter value 1:12
Enter value 2:345
Enter value 3:PFB
Enter value 4:12345
Enter value 5:Aditya
The list given as input by the user is : ['12', '345', 'PFB', '12345', 'Aditya']
使用 While 循环获取一个列表作为用户输入
当用户想要停止输入值时,我们可以要求用户输入一个特殊的值,而不是要求用户输入值的总数。之后,我们可以继续接受输入,直到用户给出特定的值作为输入信号,表明已经没有值了。我们可以使用 python 中的 while 循环来做到这一点。
在这个方法中,我们将首先创建一个空列表和一个布尔变量标志。我们将初始化标志为真。这里,flag 将作为 while 循环中的决策变量。之后,我们将开始在 while 循环中接受用户的输入,并将它们添加到列表中。如果用户输入特定的值,表明没有剩余的值,我们将把假赋给标志变量。当标志的值变为假时,它强制 while 循环终止。
在 while 循环停止执行后,我们获得了作为输入给出的所有值的列表,如下例所示。
flag = True
input_list = list()
while flag:
input_value = input("Enter the value in the list. To finish, press enter key without any input:\n")
if input_value == "":
flag = False
continue
input_list.append(input_value)
print("The list given as input by the user is :", input_list)
输出:
Enter the value in the list. To finish, press enter key without any input:
12
Enter the value in the list. To finish, press enter key without any input:
23
Enter the value in the list. To finish, press enter key without any input:
Aditya
Enter the value in the list. To finish, press enter key without any input:
567
Enter the value in the list. To finish, press enter key without any input:
The list given as input by the user is : ['12', '23', 'Aditya', '567']
只需使用 Input()方法一次,就可以获得一个列表作为用户输入
我们知道接受用户输入在时间和资源方面是很昂贵的,因为程序在接受用户输入时必须进行系统调用。因此,为了最大化程序的效率,我们可以避免多次使用 input()函数,同时将一个列表作为用户输入。
为此,我们将要求用户输入列表中的所有值,用空格字符分隔它们。将空格分隔的值作为输入后,我们将使用 python 字符串分割操作来获得所有输入值的列表。这可以在下面的例子中观察到。
input_values = input("Enter the values in the list separated by space:\n")
input_list = input_values.split()
print("The list given as input by the user is :", input_list)
输出:
Enter the values in the list separated by space:
12 345 Aditya PFB 123345
The list given as input by the user is : ['12', '345', 'Aditya', 'PFB', '123345']
结论
在本文中,我们看到了在 python 中获取列表作为用户输入的不同方法。要了解如何在 Python 中从文件中获取输入,您可以阅读这篇关于 Python 中的文件处理的文章。
如何在 Python 中处理错误和异常
原文:https://www.pythonforbeginners.com/error-handling/how-to-handle-errors-and-exceptions-in-python
错误和异常
如果您(并且您将会)编写不工作的代码,您将会得到一个错误消息。
什么是例外?
异常是你第一次运行程序后得到的结果。
不同的误差
Python 中有不同种类的错误,这里有一些:
ValueError,TypeError,NameError,IOError,EOError,SyntaxError
此输出显示一个名称错误:
>>> print 10 * ten
Traceback (most recent call last):
File "", line 1, in
NameError: name 'ten' is not defined
and this output show it's a TypeError
>>> print 1 + 'ten'
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for +: 'int' and 'str'
试着除了
Python 中有一种方法可以帮助你解决这个问题:尝试 except
#Put the code that may be wrong in a try block, like this:
try:
fh = open("non_existing_file")
#Put the code that should run if the code inside the try block fails, like this:
except IOError:
print "The file does not exist, exiting gracefully"
#Putting it together, it will look like this:
try:
fh = open("non_existing_file")
except IOError:
print "The file does not exist, exiting gracefully"
print "This line will always print"
搬运 EOFErrors
import sys
try:
name = raw_input("what is your name?")
except EOFError:
print "
You did an EOF... "
sys.exit()
If you do an ctrl+d, you will get an output like this:
>>what is your name?
>>You did an EOF...
处理键盘中断
try:
name = raw_input("Enter your name: ")
print "You entered: " + name
except KeyboardInterrupt:
print "You hit control-c"
If you press ctrl+c, you will get an output like this:
>>Enter your name: ^C
>>You hit control-c
处理值错误
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
关于所有 Python 内置异常的完整列表,请参见这篇帖子
如何在 Python 3 中连接字符串
原文:https://www.pythonforbeginners.com/python-strings/how-to-join-strings-in-python-3
程序员注定要处理大量的字符串数据。这部分是因为计算机语言与人类语言紧密相连,我们用一种语言创造另一种语言,反之亦然。
因此,尽早掌握使用字符串的细节是一个好主意。在 Python 中,这包括学习如何连接字符串。
操纵字符串似乎令人生畏,但是 Python 语言包含了使这一复杂任务变得更容易的工具。在深入 Python 的工具集之前,让我们花点时间研究一下 Python 中字符串的属性。
一点弦理论
您可能还记得,在 Python 中,字符串是字符数据的数组。
关于字符串的重要一点是,它们在 Python 语言中是不可变的。这意味着一旦创建了 Python 字符串,就不能更改。更改字符串需要创建一个全新的字符串,或者覆盖旧的字符串。
我们可以通过创建一个新的字符串变量来验证 Python 的这个特性。如果我们试图改变字符串中的一个字符,Python 会给我们一个回溯错误。
>>> my_string = "Python For Beginners"
>>> my_string[0]
'P'
>>> my_string[0] = 'p'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
在编写 Python 代码时,牢记字符串的不可改变性是一个好主意。
虽然您不能在 Python 中更改字符串,但是您可以连接它们,或者追加它们。Python 附带了许多工具来简化字符串的处理。
在这一课中,我们将讲述连接字符串的各种方法,包括字符串连接。说到连接字符串,我们可以利用 Python 操作符和内置方法。
随着学生的进步,他们可能会以这样或那样的方式使用这些技术。各有各的目的。
用“+”运算符连接字符串
串联是将两个或多个字符串连接在一起以创建一个新的字符串的行为。
在 Python 中,可以使用“+”运算符连接字符串。类似于数学等式,这种连接字符串的方式非常简单,允许将许多字符串“相加”在一起。
让我们来看一些例子:
# joining strings with the '+' operator
first_name = "Bilbo"
last_name = "Baggins"
# join the names, separated by a space
full_name = first_name + " " + last_name
print("Hello, " + full_name + ".")
在我们的第一个例子中,我们创建了两个字符串,first_name 和 last_name,然后使用'+'操作符将它们连接起来。为了清楚起见,我们在名称之间添加了空格。
运行该文件时,我们会在命令提示符下看到以下文本:
Hello, Bilbo Baggins.
示例末尾的 print 语句显示了连接字符串如何生成更易读的文本。通过串联的力量添加标点符号,我们可以创建更容易理解、更容易更新、更容易被其他人使用的 Python 程序。
让我们看另一个例子。这次我们将利用 for 循环来连接字符串数据。
# some characters from Lord of the Rings
characters = ["Frodo", "Gandalf", "Sam", "Aragorn", "Eowyn"]
storyline = ""
# loop through each character and add them to the storyline
for i in range(len(characters)):
# include "and" before the last character in the list
if i == len(characters)-1:
storyline += "and " + characters[i]
else:
storyline += characters[i] + ", "
storyline += " are on their way to Mordor to destroy the ring."
print(storyline)
这个更高级的例子展示了如何使用串联从 Python 列表中生成人类可读的文本。使用 for 循环,角色列表(取自《指环王》系列小说)被一个接一个地加入到故事情节字符串中。
这个循环中包含了一个条件语句,用来检查我们是否到达了字符列表中的最后一个对象。如果有的话,还要加上一个“和”,以便最终文本更加清晰易读。我们也一定会包括我们的牛津逗号,以增加可读性。
以下是最终输出:
Frodo, Gandalf, Sam, Aragorn, and Eowyn, are on their way to Mordor to destroy the ring.
除非两个对象都是字符串,否则这个方法不起作用。例如,试图将一个字符串与一个数字连接会产生一个错误。
>>> string = "one" + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
如您所见,Python 只允许我们将一个字符串连接到另一个字符串。作为程序员,我们的工作就是理解我们正在使用的语言的局限性。在 Python 中,如果我们希望避免任何错误,我们需要确保我们连接了正确类型的对象。
用“+”运算符连接列表
“+”运算符也可以用于连接一个或多个字符串数据列表。例如,如果我们有三个列表,每个列表都有自己唯一的字符串,我们可以使用'+'操作符来创建一个新的列表,组合所有三个列表中的元素。
hobbits = ["Frodo", "Sam"]
elves = ["Legolas"]
humans = ["Aragorn"]
print(hobbits + elves + humans)
如您所见,运算符“+”有许多用途。有了它,Python 程序员可以轻松地组合字符串数据和字符串列表。
将字符串与。join()方法
如果你在 Python 中处理一个 iterable 对象,你可能会想要使用。加入()方法。一个可迭代的对象,比如一个字符串或者一个列表,可以很容易地用连接起来。join() 方法。
任何 Python iterable 或序列都可以使用来连接。join() 方法。这包括列表和字典。
。join() 方法是一个字符串实例方法。语法如下:
string _ name . join(iterable)
这里有一个使用的例子。join() 方法连接一列字符串:
numbers = ["one", "two", "three", "four", "five"]
print(','.join(numbers))
在命令提示符下运行程序,我们将看到以下输出:
one,two,three,four,five
。join() 方法将返回一个新字符串,该字符串包含 iterable 中的所有元素,由一个分隔符连接。在前面的例子中,分隔符是逗号,但是任何字符串都可以用来连接数据。
numbers = ["one", "two", "three", "four", "five"]
print(' and '.join(numbers))
我们也可以使用这种方法连接字母数字数据列表,使用空字符串作为分隔符。
title = ['L','o','r','d',' ','o','f',' ','t','h','e',' ','R','i','n','g','s']
print(“”.join(title))
。join() 方法也可以用来获得一个带有字典内容的字符串。使用时。join() 这样,该方法将只返回字典中的键,而不是它们的值。
number_dictionary = {"one":1, "two":2, "three":3,"four":4,"five":5}
print(', '.join(number_dictionary))
用连接序列时。join() 方法,结果将是一个包含来自两个序列的元素的字符串。
使用“*”运算符复制字符串
如果需要连接两个或更多相同的字符串,可以使用' * '操作符。
使用' * '操作符,您可以将一个字符串重复任意次。
fruit = “apple”
print(fruit * 2)
“*”运算符可以与“+”运算符结合使用,以连接字符串。结合这些方法使我们能够利用 Python 的许多高级特性。
fruit1 = "apple"
fruit2 = "orange"
fruit1 += " "
fruit2 += " "
print(fruit1 * 2 + " " + fruit2 * 3)
拆分和重新连接字符串
因为 Python 中的字符串是不可变的,所以拆分和重新组合它们是很常见的。
的。 split() 方法是另一个字符串实例方法。这意味着我们可以在任何字符串对象的末尾调用它。
就像一样。加入()方法,。split() 方法使用一个分隔符来解析字符串数据。默认情况下,空白用作该方法的分隔符。
我们来看看。【split()方法在起作用。
names = "Frodo Sam Gandalf Aragorn"
print(names.split())
这段代码输出一个字符串列表。
['Frodo', 'Sam', 'Gandalf', 'Aragorn']
再举一个例子,我们来看看如何将一个句子分割成独立的部分。
story = "Frodo took the ring of power to the mountain of doom."
words = story.split()
print(words)
使用。 split() 方法返回新的 iterable 对象。因为对象是可迭代的,我们可以使用。join() 我们之前学过的将字符串“粘合”在一起的方法。
original = "Frodo took the ring of power to the mountain of doom."
words = original.split()
remake = ' '.join(words)
print(remake)
通过使用 Python 中的字符串方法,我们可以轻松地拆分和连接字符串。这些方法对于处理字符串和可迭代对象至关重要。
把松散的部分绑起来
到目前为止,您应该对字符串以及如何在 Python 3 中使用它们有了更深入的了解。完成本教程中提供的示例将是您掌握 Python 之旅的良好开端。
然而,没有学生能独自成功。这就是为什么我们编辑了 Python 为初学者提供的附加资源列表,以帮助你完成培训。
- 了解如何创建 Python 字典。
- Python 列表理解初学者指南。
只要有帮助和耐心,任何人都可以学习 Python 的基础知识。如果用 Python 连接字符串看起来令人畏惧,那么花点时间练习上面的例子。通过熟悉字符串变量和使用方法,您将很快挖掘出 Python 编程语言的无限潜力。
如何在 Python 中修改元组
原文:https://www.pythonforbeginners.com/basics/how-to-modify-a-tuple-in-python
我们知道 tuple 是一种不可变的数据类型,不像 python 字典或列表。这意味着,我们不能以任何方式修改一个元组。但是,我们可能需要修改一个元组。在这种情况下,我们没有其他选择来创建一个包含所需元素的新元组。在本文中,我们将使用不同的方式来修改元组,比如切片、打包和解包。
如何将元素追加到元组中
要在元组的末尾追加元素,我们可以使用元组串联,就像我们使用字符串串联将一个字符串追加到另一个字符串。为此,首先,我们将创建一个具有单个元素的元组,该元素必须附加到元组中。然后,我们将使用+运算符连接新元组和现有元组,如下所示。
myTuple = (1, 2, 3, 4)
print("Original Tuple is:", myTuple)
value = 5
print("Value to be added:", value)
newTuple = (5,)
myTuple = myTuple + newTuple
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4)
Value to be added: 5
Updated tuple is: (1, 2, 3, 4, 5)
我们还可以使用上面的方法将一个元素附加到元组的开头,如下所示。
myTuple = (1, 2, 3, 4)
print("Original Tuple is:", myTuple)
value = 5
print("Value to be added:", value)
newTuple = (5,)
myTuple = newTuple + myTuple
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4)
Value to be added: 5
Updated tuple is: (5, 1, 2, 3, 4)
为了向元组追加元素,我们还可以使用操作符进行打包和解包。首先,我们将使用操作符解包现有的元组。之后,我们将创建一个包含新元素的新元组,如下所示。
myTuple = (1, 2, 3, 4)
print("Original Tuple is:", myTuple)
value = 5
print("Value to be added:", value)
myTuple = (*myTuple, value)
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4)
Value to be added: 5
Updated tuple is: (1, 2, 3, 4, 5)
就像将元素追加到元组的末尾一样,我们可以使用如下的打包和解包将元素追加到元组的开头。
myTuple = (1, 2, 3, 4)
print("Original Tuple is:", myTuple)
value = 5
print("Value to be added:", value)
myTuple = (value, *myTuple)
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4)
Value to be added: 5
Updated tuple is: (5, 1, 2, 3, 4)
如何在元组中的特定位置插入元素
要在元组中的特定位置插入元素,我们可以使用切片。如果我们必须在元组的索引“I”处插入一个元素,我们将对元组进行切片并创建两个新的元组。第一元组将包含从原始元组的索引 0 到 i-1 的元素。第二元组将包含从索引“I”到最后的元素。之后,我们将创建一个元组,其中包含一个必须插入到索引 I 处的元组中的元素。然后,我们将连接这三个元组,以便在索引“I”处插入新元素,如下所示。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8)
print("Original Tuple is:", myTuple)
value = 0
print("Value to be inserted at index 3:", value)
left_tuple = myTuple[0:3]
right_tuple = myTuple[3:]
myTuple = left_tuple + (value,) + right_tuple
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8)
Value to be inserted at index 3: 0
Updated tuple is: (1, 2, 3, 0, 4, 5, 6, 7, 8)
我们还可以使用打包和解包来合并新创建的元组,如下所示。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8)
print("Original Tuple is:", myTuple)
value = 0
print("Value to be inserted at index 3:", value)
left_tuple = myTuple[0:3]
right_tuple = myTuple[3:]
myTuple = (*left_tuple, value, *right_tuple)
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8)
Value to be inserted at index 3: 0
Updated tuple is: (1, 2, 3, 0, 4, 5, 6, 7, 8)
如何通过删除元素来修改元组
为了从元组的开头删除一个元素,我们将使用剩余的元素创建一个新的元组,如下所示。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8)
print("Original Tuple is:", myTuple)
myTuple = myTuple[1:]
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8)
Updated tuple is: (2, 3, 4, 5, 6, 7, 8)
如果我们需要删除一个元组的最后一个元素,我们将按如下方式切分剩余的元素。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8)
print("Original Tuple is:", myTuple)
tupleLength = len(myTuple)
myTuple = myTuple[0:tupleLength - 1]
print("Updated tuple is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8)
Updated tuple is: (1, 2, 3, 4, 5, 6, 7)
为了删除存在于索引“I”处的元素,我们将创建原始元组的两个片段。第一个片将包含原始元组的从索引 0 到 i-1 的元素。第二元组将包含从索引“i+1”到最后的元素。之后,我们将连接新创建的元组,排除索引“I”处的元素,如下所示。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8)
print("Original Tuple is:", myTuple)
left_tuple = myTuple[0:3]
right_tuple = myTuple[4:]
myTuple = left_tuple + right_tuple
print("Updated tuple after deleting element at index 3 is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8)
Updated tuple after deleting element at index 3 is: (1, 2, 3, 5, 6, 7, 8)
如何修改元组中特定索引处的元素
为了修改元组索引“I”处的元素,我们将创建原始元组的两个切片。第一个片将包含原始元组的从索引 0 到 i-1 的元素。第二个切片将包含从索引“i+1”到最后的元素。之后,我们将通过在如下位置插入新值来更新索引“I”处的元素。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8)
print("Original Tuple is:", myTuple)
left_tuple = myTuple[0:3]
right_tuple = myTuple[4:]
myTuple = left_tuple + (100,) + right_tuple
print("Updated tuple after modifying element at index 3 is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8)
Updated tuple after modifying element at index 3 is: (1, 2, 3, 100, 5, 6, 7, 8)
我们还可以使用*运算符来合并新创建的元组,如下所示。
myTuple = (1, 2, 3, 4, 5, 6, 7, 8)
print("Original Tuple is:", myTuple)
left_tuple = myTuple[0:3]
right_tuple = myTuple[4:]
myTuple = (*left_tuple, 100, *right_tuple)
print("Updated tuple after modifying element at index 3 is:", myTuple)
输出:
Original Tuple is: (1, 2, 3, 4, 5, 6, 7, 8)
Updated tuple after modifying element at index 3 is: (1, 2, 3, 100, 5, 6, 7, 8)
结论
在本文中,我们使用了不同的方法来修改 python 中的元组。要阅读更多关于 python 编程的内容,请阅读这篇关于列表理解的文章。请继续关注更多内容丰富的文章。
如何在 Python 中打开非文本文件
原文:https://www.pythonforbeginners.com/files/how-to-open-a-non-text-file-in-python
Python 标准库提供了几个读写文本文件的工具,但是非文本文件呢?使用 Python,也可以打开非文本文件。我们可以用多种方式来做这件事。
在大多数情况下,使用标准库可以打开 Python 中的非文本文件。但是在一些模块的帮助下,我们可以更进一步。
在本教程中,我们将介绍几种用 Python 打开文本文件的方法。使用 Python 代码示例,我们将探索读取和写入二进制文件,这个过程包括将 ASCII 数据转换为字节。
我们还将向您展示如何使用用于创建和编辑图像文件的枕头模块。接下来,我们将看看如何使用波模块来读取音频数据。作为奖励,我们提供了一个用 Python 从头开始生成音频文件的例子。
我们还将研究如何使用 open ()函数来读取。csv 文件,并将其与打开非二进制文件进行比较。如果您对学习如何在 Python 中读取非文本文件感兴趣,那么您来对地方了。
文本文件和非文本文件有什么区别?
文本文件通常由单词和数字组成。这些文件有文本行,通常是用人们能读懂的语言写的(相对于机器)。
文本文件使用 ASCII ( A 美国 S 标准Code forIinformationIinterchange)字符来表示字母和数字。文本文件通常以扩展名结尾。虽然情况并不总是如此。
另一方面,非文本文件是包含 ASCII 文本以外的数据的文件。有很多这样的文件。通常,用 Python 打开一个非文本文件所需要的就是随该语言发布的标准库。但是在一两个模块的帮助下,我们可以将我们的 Python 技能提升到另一个水平。
用 Python 读写二进制(非文本)文件
二进制文件也称为非文本文件,是包含多组二进制数字(位)的文件。二进制文件将比特分成八个序列,称为一个字节。通常,这些字节代表的不是文本数据。
有了 Python,我们可以使用标准函数读写二进制文件。例如,我们可以使用 open ()函数创建一个新的二进制文件。为此,我们需要向函数传递一些特殊字符。这告诉函数我们想要在写模式 (w)和二进制模式 (b)下打开文件。
打开一个新文件后,我们可以使用 bytearray ()函数将一列数字转换成字节。bytearray()函数用于将对象转换为字节数组。可以使用写()功能将二进制数据保存到磁盘。
示例:将二进制文件写入磁盘
f = open("binary_file", 'w+b')
byte_arr = [1,2,3,4]
# convert data to a byte array
binary_format = bytearray(byte_arr)
f.write(binary_format)
f.close()
同样,我们可以使用 open ()函数在 Python 中打开一个非文本文件。当读取二进制文件类型时,需要将字符“r”和“b”传递给 open()函数。这告诉 open()函数我们打算以二进制模式读取文件。
示例:读取二进制文件
file = open("binary_file",'rb')
number = list(file.read())
print("Binary data = ", number)
file.close()
输出
Binary data = [1, 2, 3, 4]
如何将二进制数据转换为文本
使用标准的 Python 方法,可以将文本转换成二进制数据,反之亦然。使用 decode ()方法,我们可以将二进制数据转换成 ASCII 文本。这样做可以让我们获取二进制信息,并将其转换为人类可以阅读的内容。
示例:在 Python 中转换二进制数据
# binary to text
binary_data = b'Hello World.'
text = binary_data.decode('utf-8') # Change back into ASCII
print(text)
# convert text to bytes
binary_message = text.encode('utf-8')
print(type(binary_message))
binary_data = bytes([65, 66, 67]) # ASCII values for the letters A, B, and C
text = binary_data.decode('utf-8')
print(text)
在 Python 中打开图像文件
可以使用 open()函数打开图像文件。通过将结果赋给一个新变量,我们可以打开一个图像文件。在下面的例子中,我们将尝试打印以读取模式打开的图像文件的内容。
file = open("boat.jpg",'r')
print(file)
输出
<_io.TextIOWrapper name='boat.jpg' mode='r' encoding='cp1252'>
使用 Python 模块,我们可以做的不仅仅是打开图像文件。有了枕头模块,我们可以随心所欲地处理图像。
在使用枕头模块之前,您需要安装它。安装 Python 模块最简单的方法是从命令提示符或终端运行 pip。
使用以下命令安装 pip。
pip install pillow
在电脑上安装 Pillow 后,您可以打开并编辑照片和其他图像文件。使用 Pillow,我们可以读取图像文件并将其尺寸打印到控制台。
如何使用枕头模块
在我们可以使用 pillow 模块之前,我们必须让 Python 知道我们想在我们的程序中使用它。我们通过导入模块来实现这一点。在下面的例子中,我们使用来自的和来自的来包含来自 PIL (Pillow)的图像模块。
示例:用 PIL 打开图像文件
from PIL import Image
img = Image.open("boat.jpg")
#open the original image
size = img.size
print(size)
# opens the image in the default picture viewer
img.show()
Pillow 包括编辑照片的模块。使用 Pillow 附带的 ImageOps ,我们可以反转照片,并使用您计算机上的默认照片查看器显示它。
示例:使用 PIL 反转图像
from PIL import Image, ImageOps
img = Image.open("boat.jpg")
#open the original image
size = img.size
print(size)
# invert the image with ImageOps
img = ImageOps.invert(img)
# opens the image in the default picture viewer
img.show()
在 Python 中打开音频文件
Python 提供了读取和创建音频文件的工具。使用波模块,我们可以打开。wav 音频文件并检查它们的数据。在下面的例子中,我们将打开一个名为“portal.wav”的. wav 文件,并将其采样率打印到控制台。
示例:用波形模块打开一个. wav 文件
import wave
audio = wave.open("portal.wav",'r')
print("Sample Rate: ", audio.getframerate())
输出
Sample Rate: 44100
更进一步,我们可以使用 Wave 模块从头开始生成我们自己的音频文件。通过给音频帧分配一个随机值,我们可以生成一个静态噪声的音频文件。
示例:使用 Wave 模块生成音频文件
import wave, struct, math, random
# this example will generate an audio file of static noise
sample_rate = 44100.0 # hertz
duration = 1.0 # seconds
frequency = 440.0 # hertz
sound = wave.open("sound.wav",'w')
sound.setnchannels(1) # mono
sound.setsampwidth(2)
sound.setframerate(sample_rate)
for i in range(99999):
# 32767 is the maximum value for a short integer.
random_val = random.randint(-32767, 32767)
data = struct.pack('h', random_val)
sound.writeframesraw(data)
sound.close()
如何在 Python 中打开 CSV 文件
逗号分隔值文件(通常称为 CSV 文件)是存储和交换数据的便捷方式。这些文件通常包含由逗号分隔的数字和/或字母。
即使 CSV 文件不以。txt 扩展名,它们被视为文本文件,因为它们包含 ASCII 字符。作为 Python 开发人员,学习如何打开 CSV 文件是一项有用的技能。使用下面的例子来比较在 Python 中打开非文本文件和文本文件。
使用下面的示例 CSV 文件,我们将探索如何使用 Python 读取 CSV 数据。
animal_kingdom.csv
"amphibians","reptiles","birds","mammals"
"salamander","snake","owl","coyote"
"newt","turtle","bald eagle","raccoon"
"tree frog","alligator","penguin","lion"
"toad","komodo dragon","chicken","bear"
示例:使用 Open()读取 CSV 文件
with open("animal_kingdom.csv",'r') as csv_file:
file = csv_file.read()
print(file)
运行上面的代码会将 animal_kingdom.csv 的内容打印到控制台。然而,有一种更好的方法来读取 Python 中的 CSV 文件。
如何使用 CSV 模块
CSV 模块预装在 Python 中,所以不需要安装它。使用 CSV 模块可以让我们更好地控制 CSV 文件的内容。例如,我们可以使用 reader ()函数从文件中提取字段数据。
示例:使用 csv 模块读取 Python 中的 csv 文件
import csv
with open("animal_kingdom.csv",'r') as csv_file:
csvreader = csv.reader(csv_file)
# read the field names
fields = csvreader.__next__()
print('Field Names\n----------')
for field in fields:
print(field)
print('\nRows\n---------------------')
for row in csvreader:
for col in row:
print(col,end="--")
print("\n")
结论
我们研究了 Python 中处理非文本文件的各种方法。通过将 ASCII 文本转换成字节数组,我们可以创建自己的二进制文件。在 read()函数的帮助下,我们可以读取二进制数据并将其打印到控制台。
Python 模块 Pillow 是打开和编辑图像文件的绝佳选择。如果您有兴趣了解更多关于图像处理的知识,枕头模块是一个很好的起点。
Wave 模块是用 Python 发布的。用它来读写波形数据。通过一点数学知识,Wave 模块可以用来生成各种声音效果。
相关职位
如果您觉得本教程很有帮助,请点击下面的链接,了解更多关于 Python 编程的精彩世界。
- 学习 Python 读取文件操作与我们的操作指南
- Python 列表理解适合初学者
如何从 Python 字符串中删除标点符号
原文:https://www.pythonforbeginners.com/python-strings/how-to-remove-punctuation-from-a-python-string
在数据分析任务中,我们经常会遇到需要处理的文本数据,以便从数据中提取有用的信息。在文本处理过程中,我们可能必须从数据中提取或删除某些文本以使其有用,或者我们可能还需要用其他文本替换某些符号和术语以提取有用的信息。在这篇文章中,我们将学习标点符号,并看看从 python 字符串中删除标点符号的方法。
什么是标点符号?
英语语法中有几个符号,包括逗号、连字符、问号、破折号、感叹号、冒号、分号、圆括号、方括号等,这些都被称为标点符号。这些在英语中用于语法目的,但是当我们在 python 中执行文本处理时,我们通常不得不从字符串中省略标点符号。现在我们将看到在 Python 中从字符串中删除标点符号的不同方法。
使用 for 循环删除字符串中的标点符号
在这个方法中,首先我们将创建一个包含输出字符串的空 python 字符串。然后,我们将简单地遍历 python 字符串的每个字符,并检查它是否是标点符号。如果字符将是一个标点符号,我们将离开它。否则,我们将使用字符串连接将其包含在输出字符串中。
例如,在下面给出的代码中,我们将每个标点符号保存在一个名为punctuation的字符串中。我们使用 for 循环遍历输入字符串myString,然后检查该字符是否出现在标点符号字符串中。如果不存在,该字符将包含在输出字符串newString中。
punctuation= '''!()-[]{};:'"\, <>./[[email protected]](/cdn-cgi/l/email-protection)#$%^&*_~'''
print("The punctuation marks are:")
print(punctuation)
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
newString=""
for x in myString:
if x not in punctuation:
newString=newString+x
print("Output String is:")
print(newString)
输出
The punctuation marks are:
!()-[]{};:'"\, <>./[[email protected]](/cdn-cgi/l/email-protection)#$%^&*_~
Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners
使用正则表达式移除 python 字符串中的标点符号
我们还可以使用正则表达式在 python 中删除字符串中的标点符号。为此,我们将使用 python 中的re模块,它提供了使用正则表达式处理字符串的函数。
在此方法中,我们将使用re.sub()方法用空字符串替换每个非字母数字或空格字符,因此所有标点符号都将被删除。
sub() 方法的语法是re.sub(pattern1, pattern2,input_string),其中pattern1表示将被替换的字符模式。在我们的例子中,我们将提供一个模式来表示不是字母数字或空格字符的字符。pattern2是pattern1中的字符将被替换的最终模式。在我们的例子中,pattern2将是空字符串,因为我们只需从 python 字符串中删除标点符号。input_string是必须被处理以去除标点符号的字符串。
示例:
import re
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
emptyString=""
newString=re.sub(r'[^\w\s]',emptyString,myString)
print("Output String is:")
print(newString)
输出
Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners
使用 replace()方法移除 python 字符串中的标点符号
在字符串上调用 Python string replace()方法时,该方法将初始模式和最终模式作为参数,并返回一个结果字符串,其中初始模式中的字符被最终模式中的字符替换。
我们可以使用 replace()方法,通过用空字符串替换每个标点符号来删除 python 字符串中的标点符号。我们将逐个迭代整个标点符号,用文本字符串中的空字符串替换它。
replace()方法的语法是replace(character1,character2),其中character1是将被参数character2中给定字符替换的字符。在我们的例子中,character1将包含标点符号,而character2将是一个空字符串。
punctuation= '''!()-[]{};:'"\, <>./[[email protected]](/cdn-cgi/l/email-protection)#$%^&*_~'''
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
emptyString=""
for x in punctuation:
myString=myString.replace(x,emptyString)
print("Output String is:")
print(myString)
输出:
Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners
使用 translate()方法移除 python 字符串中的标点符号
translate() 方法根据作为参数提供给函数的翻译表,用新字符替换输入字符串中指定的字符。翻译表应该包含哪些字符必须被哪些字符替换的映射。如果表中没有任何字符的映射,该字符将不会被替换。
translate()方法的语法是 translate( translation_dictionary),其中translation_dictionary将是一个 python 字典,包含输入字符串中的字符到它们将被替换的字符的映射。
要创建翻译表,我们可以使用maketrans()方法。该方法将字符串中需要替换的起始字符、结束字符和需要删除的字符以字符串的形式作为可选输入,并返回一个作为翻译表的 python 字典。
maketrans()方法的语法是maketrans(pattern1,pattern2,optional_pattern)。这里的pattern1将是一个包含所有要被替换的字符的字符串。pattern2将是一个字符串,其中包含了pattern1中的字符将被替换的字符。这里pattern1的长度应该等于pattern2的长度。optional_pattern是包含必须从输入文本中删除的字符的字符串。在我们的例子中,pattern1和pattern2将是空字符串,而optional_pattern将是包含标点符号的字符串。
为了创建一个从 python 字符串中删除标点符号的转换表,我们可以将maketrans() 函数的前两个参数留空,并将标点符号包含在要排除的字符列表中。这样,所有的标点符号将被删除,输出字符串将获得。
例子
punctuation= '''!()-[]{};:'"\, <>./[[email protected]](/cdn-cgi/l/email-protection)#$%^&*_~'''
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
emptyString=""
translationTable= str.maketrans("","",punctuation)
newString=myString.translate(translationTable)
print("Output String is:")
print(newString)
输出
Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners
结论
在本文中,我们看到了如何使用 for 循环、正则表达式和内置的字符串方法(如 replace()和 translate())在 python 中删除字符串中的标点符号。请继续关注更多内容丰富的文章。
如何在 Python 中反转列表
原文:https://www.pythonforbeginners.com/lists/how-to-reverse-a-list-in-python
python 中的列表是最常用的数据结构。我们经常需要反转一个列表,从列表中删除一个元素,向列表中添加或插入一个元素,或者在 python 中合并两个列表。在这篇文章中,我们将看看在 python 中反转列表的不同方法。
使用循环反转列表
反转列表最简单的方法是以相反的顺序遍历列表。在迭代时,我们可以将每个遍历的元素添加到一个新列表中,这将创建一个反向列表。为此,首先我们将计算列表的长度,然后我们将以相反的顺序遍历列表,我们将使用 append()方法将每个遍历的元素追加到新列表中,如下所示。
myList=[1,2,3,4,5,6,7]
print("Original List is:",myList)
list_len=len(myList)
newList=[]
for i in range(list_len):
newList.append(myList[list_len-1-i])
print("reversed list is:",newList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
reversed list is: [7, 6, 5, 4, 3, 2, 1]
虽然我们已经用上面的方法创建了一个反向列表,但是在迭代之前计算列表的长度是有开销的。
我们也可以使用 while 循环来反转列表。为此,在每次迭代中,我们将使用 pop()方法从原始列表中弹出一个元素,直到列表变空,如下所示。
myList=[1,2,3,4,5,6,7]
print("Original List is:",myList)
newList=[]
while myList: #empty list points to None and will break the loop
temp=myList.pop()
newList.append(temp)
print("reversed list is:",newList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
reversed list is: [7, 6, 5, 4, 3, 2, 1]
这种反转列表的方式会删除原始列表中的所有元素。因此,只有当程序中不再需要原始列表时,才应该使用这种方式来反转 python 中的列表。
使用切片反转列表
切片是一种操作,借助它我们可以访问、更新或删除列表中的元素。我们也可以使用切片来反转列表,如下所示。
myList=[1,2,3,4,5,6,7]
print("Original List is:",myList)
newList=myList[::-1]
print("reversed list is:",newList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
reversed list is: [7, 6, 5, 4, 3, 2, 1]
使用 reversed()方法
我们可以使用 reversed()方法来反转列表。reversed()方法将一个类似迭代器的列表作为输入,并返回一个反向迭代器。之后,我们可以使用 for 循环从迭代器创建反向列表,如下所示。
myList=[1,2,3,4,5,6,7]
print("Original List is:",myList)
newList=[]
reverse_iterator=reversed(myList)
for i in reverse_iterator:
newList.append(i)
print("reversed list is:",newList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
reversed list is: [7, 6, 5, 4, 3, 2, 1]
我们也可以使用列表理解来代替 for 循环,从反向迭代器创建一个列表,如下所示。
myList=[1,2,3,4,5,6,7]
print("Original List is:",myList)
reverse_iterator=reversed(myList)
newList= [i for i in reverse_iterator]
print("reversed list is:",newList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
reversed list is: [7, 6, 5, 4, 3, 2, 1]
我们也可以使用 list()构造函数直接将反向迭代器转换成列表,如下所示。
myList=[1,2,3,4,5,6,7]
print("Original List is:",myList)
reverse_iterator=reversed(myList)
newList=list(reverse_iterator)
print("reversed list is:",newList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
reversed list is: [7, 6, 5, 4, 3, 2, 1]
使用 Reverse()方法反转列表
在上面描述的所有方法中,我们创建了一个新的列表,以逆序存储原始列表的值。现在,我们将了解如何在适当的位置反转列表,即如何反转将作为输入提供给我们的同一列表。
要以这种方式反转列表,我们可以使用 reverse()方法。在列表上调用 reverse()方法时,将按如下方式反转元素的顺序。
myList=[1,2,3,4,5,6,7]
print("Original List is:",myList)
myList.reverse()
print("reversed list is:",myList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
reversed list is: [7, 6, 5, 4, 3, 2, 1]
结论
在本文中,我们看到了如何使用 for 循环、切片、列表理解、reverse()方法和 reversed()方法在 python 中反转列表。请继续关注更多内容丰富的文章。
如何在 Python 中反转字符串
原文:https://www.pythonforbeginners.com/basics/how-to-reverse-a-string-in-python
我们可以在 python 中对字符串执行很多操作。这些操作包括分割字符串、字符串连接、反转字符串、分割字符串等等。在本文中,我们将使用不同的方法在 python 中反转一个字符串。
使用切片反转字符串
在 python 中反转字符串的第一个也是最简单的方法是使用切片。我们可以使用语法string_name[ start : end : interval ]创建任何字符串的切片,其中 start 和 end 是必须从字符串切片的子字符串的开始和结束索引。interval 参数用于以指定的间隔选择字符。
要使用切片来反转整个字符串,我们将把开始和结束参数留空。这将导致从整个字符串创建切片。interval 参数将被指定为-1,以便连续的字符以相反的顺序包含在分片的字符串中。这可以从下面的例子中理解。
myString = "PythonForBeginners"
reversedString = myString[:: -1]
print("Original String is:", myString)
print("Reversed String is:", reversedString)
输出:
Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP
使用 for 循环反转字符串
要使用 for 循环反转字符串,我们将首先计算字符串的长度。然后,我们将创建一个新的空字符串。然后,我们将从末尾到开始逐个字符地访问字符串,并将它添加到新创建的字符串中。这将导致创建一个新字符串,该字符串中的字符与原始字符串的顺序相反。从下面的例子可以很容易理解这一点。
myString = "PythonForBeginners"
reversedString = ""
strlen = len(myString)
for count in range(strlen):
character = myString[strlen - 1 - count]
reversedString = reversedString + character
print("Original String is:",myString)
print("Reversed String is:", reversedString)
输出:
Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP
使用 Python 列表反转字符串
我们也可以在 python 中使用 list 来反转一个字符串。在这个方法中,首先,我们将把字符串转换成一个字符列表,并创建一个新的空字符串。之后,我们将从列表的末尾逐个取出字符,然后我们将执行字符串连接来将字符添加到新字符串中。
这样,将创建一个新字符串,它将是原始字符串的反向。这可以如下进行。
myString = "PythonForBeginners"
charList=[]
charList[:0] = myString
reversedString = ""
strlen = len(charList)
for count in range(strlen):
character = charList.pop()
reversedString = reversedString+character
print("Original String is:", myString)
print("Reversed String is:", reversedString)
输出:
Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP
使用递归反转字符串
为了使用递归来反转一个字符串,我们将使用下面的过程。
假设我们定义了一个函数 reverseString(input_string)来反转字符串。首先我们将检查 input_string 是否为空,如果是,那么我们将返回 input_string。否则,我们将从 input_string 中取出最后一个字符,并为剩余部分调用 reverseString()函数,并将它的输出连接在 input_string 的最后一个字符之后,如下所示。
myString = "PythonForBeginners"
def reverseString(input_string):
strlen = len(input_string)
if strlen == 0:
return ""
else:
last = input_string[-1]
rest = input_string[0:strlen - 1]
return last + reverseString(rest)
reversedString = reverseString(myString)
print("Original String is:", myString)
print("Reversed String is:", reversedString)
输出:
Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP
使用 reversed()方法
reversed()方法返回作为输入参数传递给它的任何可迭代对象的反向迭代器。我们可以使用反向迭代器来创建输入字符串的反向。我们将首先创建一个空字符串,然后通过迭代 reversed()函数返回的反向迭代器以逆序添加字符,如下所示。
myString = "PythonForBeginners"
reverse_iterator = reversed(myString)
reversedString = ""
for char in reverse_iterator:
reversedString = reversedString + char
print("Original String is:", myString)
print("Reversed String is:", reversedString)
输出:
Original String is: PythonForBeginners
Reversed String is: srennigeBroFnohtyP
结论
在本文中,我们研究了在 python 中反转字符串的不同方法。。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
如何用 Python 将字典保存到文件中
原文:https://www.pythonforbeginners.com/dictionary/how-to-save-dictionary-to-file-in-python
python 字典用于存储程序中的键值映射。有时,我们可能需要将字典直接存储在文件中。在本文中,我们将讨论如何用 Python 将字典直接保存到文件中。
使用 Python 中的字符串将字典保存到文件中
要将字典保存到文件中,我们可以先将字典转换为字符串。之后,我们可以将字符串保存在文本文件中。为此,我们将遵循以下步骤。
- 首先,我们将使用 str()函数将字典转换为字符串。str()函数接受一个对象作为输入,并返回它的字符串表示。
- 获得字典的字符串表示后,我们将使用 open()函数以写模式打开一个文本文件。open()函数将文件名和模式作为输入参数,并返回一个文件流对象,比如 myFile。
- 在获得文件流对象 myFile 之后,我们将使用 write()方法将字符串写入文本文件。在 file 对象上调用 write()方法时,该方法将一个字符串作为输入参数,并将其写入文件。
- 在执行 write()方法之后,我们将使用 close()方法关闭文件流。
按照上面的步骤,您可以将字典以字符串形式保存到文件中。将字典保存到文件后,您可以通过打开文件来验证文件内容。在下面的代码中,我们首先将一个 python 字典保存到一个文件中。
myFile = open('sample.txt', 'w')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
myFile.write(str(myDict))
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the dictionary is:")
print(myFile.read())
输出:
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the file after saving the dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
用 Python 将字典以二进制格式保存到文件中
我们可以直接以二进制格式存储字典,而不是以文本格式存储字典。为此,我们将使用 Python 中的 pickle 模块。为了使用 pickle 模块将字典保存到文件中,我们将遵循以下步骤。
- 首先,我们将使用 open()函数以写二进制(wb)模式打开一个文件。open()函数将文件名和模式作为输入参数,并返回一个文件流对象,比如 myFile。
- pickle 模块为我们提供了 dump()方法,在该方法的帮助下,我们可以将二进制格式的字典保存到文件中。dump()方法将一个对象作为第一个输入参数,将一个文件流作为第二个输入参数。执行后,它将对象以二进制格式保存到文件中。我们将把字典作为第一个参数,把 myFile 作为第二个输入参数传递给 dump()方法。
- 在执行 dump()方法之后,我们将使用 close()方法关闭文件。
以下是用 python 将字典保存到文件中的 python 代码。
import pickle
myFile = open('sample_file', 'wb')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
pickle.dump(myDict,myFile)
myFile.close()
将字典保存为二进制格式后,我们可以使用 pickle 模块中的 load()方法检索它。load()方法将包含二进制形式的 python 对象的文件流作为其输入参数,并返回 Python 对象。使用 dump()方法将字典保存到文件后,我们可以从文件中重新创建字典,如下所示。
import pickle
myFile = open('sample_file', 'wb')
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
pickle.dump(myDict,myFile)
myFile.close()
myFile = open('sample_file', 'rb')
print("The content of the file after saving the dictionary is:")
print(pickle.load(myFile))
输出:
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the file after saving the dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
结论
在本文中,我们讨论了用 python 将字典保存到文件的两种方法。想了解更多关于字典的知识,可以阅读这篇关于 python 中字典理解的文章。
如何通过 Python 在文本文件中搜索字符串
原文:https://www.pythonforbeginners.com/strings/how-to-search-for-a-string-in-a-text-file-through-python
在这篇文章中,我们将探索在文本文件中搜索字符串的各种方法。使用 Python 3 编写的例子,我们将演示如何打开和读取文本文件和 CSV 文件。打开后,我们可以在这些文件中搜索特定的字符串。
文本文件可以保存许多不同类型的数据。需要在这些文件中搜索字符串的情况并不少见。Python 标准库包括许多函数和模块,简化了在文本文件中搜索字符串的过程。
使用 readlines ()方法在文本文件中搜索字符串
在我们可以在文本文件中搜索字符串之前,我们需要读取文件的内容。 readlines ()方法读取一个文件的数据并返回它所包含的行的列表。列表中的每个元素将包含文本文件中的一行。
在我们的第一个例子中,我们将创建一个新的文本文件,并在其中搜索特定的字符串。我们将使用 readlines()方法来读取文件的数据。然后我们将这些数据分配给一个名为 lines 的变量。
有了行列表,我们可以使用 for 循环遍历文本文件,搜索包含字符串“magician”的任何行。如果找到一个,就将整行打印到终端。
示例:使用 readlines() 在文本文件中查找字符串
# create a new text file and write some text
text_file = open("text_file.txt",'w')
text_file.write("The magician appeared without a sound.")
text_file.close()
# safely open the text file we created and search for a string
with open("text_file.txt",'r') as text_file:
lines = text_file.readlines()
for line in lines:
if "magician" in line:
print(line)
输出
The magician appeared without a sound.
使用 read ()方法在文本文件中搜索字符串
在 Python 中,我们可以使用的另一种从文本文件中读取数据的方法是 read ()。这个方法返回一个包含文件内容的字符串。
使用 read()方法,我们将在下面的文本文件中搜索单词“魔术师”如果我们要找的单词在文本文件中,程序会通过在控制台上打印“True”来让我们知道。
魔术师 _ 故事. txt
魔术师无声无息的出现了。她紧张地笑了笑。她听到时钟滴答作响
,意识到自从她最后一次见到魔术师之后,他已经变了形。朱莉娅觉得她的心跳到了嗓子眼。
示例:使用 read()方法搜索文本文件
story_file = open("magic_story.txt",'r')
story_text = story_file.read()
story_file.close()
if "magician" in story_text:
print("True")
输出
True
统计字符串在文本文件中出现的次数
接下来,使用前面例子中的故事,我们将演示如何计算一个单词在文本文件中出现的次数。有时,一个文本文件包含一个单词或短语的许多实例。使用 Python,可以计算一个字符串在文本文档中出现的次数。
在下面的例子中,一个带有语句的 Python **用于打开文本文件并读取其内容。以这种方式打开文件可以确保文件被安全地处理和正确地关闭。随着文件的打开,数据通过 readlines ()方法被转换成一个字符串列表。
最后,使用一个 f 字符串打印结果。**
示例:计算包含特定字符串的文本行数
with open("magic_story.txt",'r') as text_file:
lines = text_file.readlines()
count = 0
for line in lines:
if "magician" in line:
count += 1
print(f"Found 'magician' {count} times.")
输出
Found 'magician' 2 times.
在文本文件中查找包含字符串的所有行
到目前为止,我们已经了解了如何在文本文件中搜索字符串。但是如果我们需要更多的信息呢?假设我们想要记录包含字符串的文本行。我们如何用 Python 做到这一点?
从文件中提取行的最简单的方法可能是使用列表。对于下一个例子,我们将在文档中搜索一个字符串,并使用 append ()方法将包含我们正在寻找的字符串的任何行添加到一个列表中。
append()方法用于向列表中添加元素。一旦一个元素被添加到列表中,就可以使用括号来访问它。通过将元素的索引放在列表变量后面的括号中,我们可以获得对该元素的引用。
我们还需要使用剥离()方法来移除每行末尾的换行符。在这个练习中,我们将使用以下文本,节选自 T.S .艾略特的《透明人》。
hollow_men.txt
欲望
与效力
与存在
之间的痉挛
本质
与下凡
之间落下阴影
示例:使用列表存储文本行
file = open("hollow_men.txt",'r')
lines = file.readlines()
file.close()
lines_we_want = []
for i in range(len(lines)):
if "Between" in lines[i]:
lines_we_want.append(lines[i].strip("\n"))
print(lines_we_want)
输出
['Between the desire', 'Between the potency', 'Between the essence']
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
使用 find ()方法在文本文件中搜索字符串
find ()方法返回一个字符串第一个实例的位置。如果没有找到字符串,这个方法返回值-1。我们可以用这个方法来检查一个文件是否包含一个字符串。
示例:使用 find()方法
text = "Hello World"
print(text.find("Hello"))
print(text.find("World"))
print(text.find("Goodbye"))
输出
0
6
-1
首先,我们可以用一些示例文本创建一个新的文本文件。其次,我们将使用带有语句的打开文件。读取文件内容后,我们将数据存储为一个新变量。最后,使用 find()方法,我们将尝试定位单词“魔术师”的第一个实例并打印结果。
示例:使用 find()方法在文本文件中搜索字符串
# create a new texts file and write some text
text_file = open("new_file.txt",'w')
text_file.write("The magician appeared without a sound.")
text_file.close()
# safely open the text file we created and search for a string
with open("new_file.txt",'r') as text_file:
text_data = text_file.read()
print(text_data.find("magician"))
输出
4
如何在 CSV 文件中搜索字符串数据
CSV 文件以纯文本形式存储数据。这些文件通常包含由逗号分隔的字符串或数字。这就是为什么我们称它们为逗号分隔值文件。这些 CSV 文件使得程序交换信息更加容易。
Python 附带了一个用于读取 CSV 文件的模块。 csv 模块包括从这些文件类型中提取数据的特殊方法。其中一种方法是读本()。
假设我们的员工交给我们一个文件,其中包含一个网站的用户数据列表。我们的工作是在这些数据中搜索特定的用户。我们将首先搜索一个名为“the_magician”的用户。
account_info.csv
用户名,邮箱,加入日期
cranky_jane,【邮箱保护】,01-21-2021
the_magician,【邮箱保护】,10-10-2020
军士 _ 佩珀,【邮箱保护】,05-15-2020
在找到用户句柄之前,我们需要读取文件数据。通过将 reader ()方法与 for 循环相结合,可以迭代包含在文本文件中的 CSV 数据行。如果我们遇到一行包含我们要找的用户名,我们将打印该行的数据。
示例:在 CSV 文件中搜索字符串
import csv
# the string we want to find in the data
username = "the_magician"
with open("account_info.csv",'r') as data_file:
# create a reader object from the file data
reader = csv.reader(data_file)
# search each row of the data for the username
for row in reader:
if username in row:
print(row)
输出
['the_magician', '[[email protected]](/cdn-cgi/l/email-protection)', '10-10-2020']
如果我们想在 CSV 文件中搜索多个用户名,该怎么办?我们可以通过创建一个我们想要搜索的用户名列表来做到这一点。将每一行与用户名列表进行比较,就有可能找到我们要查找的帐户数据。
示例:在 CSV 文件中搜索字符串列表
import csv
# the strings we want to find in the data
usernames = ["the_magician","cranky_jane"]
with open("account_info.csv",'r') as data_file:
# create a reader object from the file data
reader = csv.reader(data_file)
# search each row of the data for the username
for row in reader:
for username in usernames:
if username in row:
print(row)
输出
['cranky_jane', '[[email protected]](/cdn-cgi/l/email-protection)', '01-21-2021']
['the_magician', '[[email protected]](/cdn-cgi/l/email-protection)', '10-10-2020']
结论
有了合适的工具,完成一项工作就容易多了。这就是为什么了解 Python 的许多特性非常重要。为了在文本文件中搜索字符串,我们需要学习像 readlines ()和 find ()这样的方法。这些都是通用的方法,非常适合解决许多不同的问题。
相关职位
如果您想了解更多关于 Python 开发的知识,请点击这些链接,查看 Python 为初学者提供的其他优秀教程。
- 使用 Python 读取文件方法打开文本文件
- 如何给程序添加一个 Python 注释
如何在 Python 中分割字符间的字符串
原文:https://www.pythonforbeginners.com/basics/how-to-split-a-string-between-characters-in-python
在这篇 Python 拆分字符串的指南中,我们将探索使用该语言精确拆分字符串的各种方法。当我们在 Python 中分割字符之间的字符串时,可以从整体中提取字符串的一部分(也称为子串)。
学习如何拆分字符串对任何 Python 程序员都是有用的。无论您打算将 Python 用于 web 开发、数据科学还是自然语言处理,拆分字符串都将是一个常规操作。我们将遵循几个在 Python 中获取子字符串的过程。首先,我们来看看拼接符号和分割()函数。之后,我们将研究更高级的技术,比如 regex 。
用切片符号在字符之间分割字符串
谈到拆分字符串,对于 Python 开发人员来说,切片符号是一个显而易见的选择。使用切片符号,我们可以找到字符串的一个子部分。
示例:用切片符号分割字符串
text = """BERNARDO
Well, good night.
If you do meet Horatio and Marcellus,
The rivals of my watch, bid them make haste."""
speaker = text[:8]
print(speaker)
输出
BERNARDO
按字符位置拆分字符串
要使用这种方法,我们需要知道要分割的子串的开始和结束位置。我们可以使用 index ()方法来查找字符串中某个字符的索引。
举例:如何找到字符串中某个字符的索引
sentence = "Jack and Jill went up the hill."
index1 = sentence.index("J",0)
print(index1)
index2 = sentence.index("J",1)
print(index2)
输出
0
9
使用 split()的快速指南
Python 标准库附带了一个用于拆分字符串的函数: split ()函数。这个函数可以用来分割字符之间的字符串。split()函数有两个参数。第一个叫做分隔符,它决定使用哪个字符来分割字符串。
split()函数返回原始字符串的子字符串列表。通过向 split()函数传递不同的值,我们可以用多种方式拆分字符串。
使用 split()函数拆分字符串
我们可以通过使用 split ()函数中的分隔符来指定拆分字符串的字符。默认情况下,split()将使用空格作为分隔符,但是如果我们愿意,我们可以自由地提供其他字符。
示例:用空格分割字符串
sentence = "The quick brown fox jumps over the lazy dog."
# split a string using whitespace
words = sentence.split()
print(words)
输出
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
示例:拆分由逗号分隔的字符串
rainbow = "red,orange,yellow,green,blue,indigo,violet"
# use a comma to separate the string
colors = rainbow.split(',')
print(colors)
输出
['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
使用带多个参数的 split()
使用 split()函数,我们还可以控制拆分多少行文本。这个函数接受第二个参数: maxsplit 。这个变量告诉 split()函数要执行多少次拆分。
示例:拆分多行文本
text = """HORATIO
Before my God, I might not this believe
Without the sensible and true avouch
Of mine own eyes."""
lines = text.split(maxsplit=1)
print(lines)
输出
['HORATIO', 'Before my God, I might not this believe\nWithout the sensible and true avouch\nOf mine own eyes.']
因为我们将 maxsplit 的值设置为 1,所以文本被分成两个子字符串。
如何在两个相同的字符之间拆分字符串
如果我们有一个由多个相同字符分割的文本,我们可以使用 split()函数来分隔字符之间的字符串。
示例:使用符号分隔字符串
nums = "1--2--3--4--5"
nums = nums.split('--')
print(nums)
输出
['1', '2', '3', '4', '5']
如何找到两个符号之间的字符串
我们可以将 index()函数与切片符号结合起来,从字符串中提取一个子字符串。index()函数将给出子串的开始和结束位置。一旦我们知道了符号的位置(本例中是、的、T3),我们将使用切片符号提取字符串。
示例:用 index()函数提取子串
# extract the substring surrounded by $'s from the text
text = "Lorem ipsum dolor sit amet, $substring$ adipisicing elit."
start = text.index('$')
end = text.index('$',start+1)
substring = text[start+1:end]
print(f"Start: {start}, End: {end}")
print(substring)
输出
Start: 28, End: 38
substring
如何使用正则表达式在字符间拆分字符串
正则表达式是在字符串或文本中搜索模式的一种便捷方式。因为正则表达式模式(regex)非常通用,所以可以用来创建非常有针对性的搜索。
Python 自带了re库。使用 regex,我们可以仔细搜索文本,查找特定的单词、短语,甚至是特定长度的单词。
示例:使用正则表达式搜索字符串
import re
text="""The Fulton County Grand Jury said Friday an investigation
of Atlanta's recent primary election produced "no evidence" that
any irregularities took place."""
# search the text for words that are 14 characters long
match= re.search(r"\w{14}", text)
print(match.group())
# search the text for the word "Atlanta"
atlanta = re.search(r"Atlanta",text)
print(atlanta.group())
输出
irregularities
Atlanta
示例:使用正则表达式查找日期
sentence= "Tony was born on May 1st 1972."
date= re.search(r"\d{4}",sentence)
print(date.group())
输出
1972
在上面的例子中,我们使用了 search() 方法来使用正则表达式模式查找子串。这个方法有两个参数。第一个是我们的 regex 模式,第二个是我们想要执行搜索的字符串。
正则表达式使用特殊字符和数字创建目标搜索。例如,我们的第一个例子使用特殊字符 \w 来搜索单词。
正则表达式的特殊字符:
- /w–搜索字母数字字符(单词)
- /d–搜索数字字符(0-9)
- /s–搜索空白字符
示例:查找字符串是否以带有正则表达式的单词开头
speech= """HAMLET
O God, your only jig-maker. What should a man do
but be merry? for, look you, how cheerfully my
mother looks, and my father died within these two hours."""
match= re.search(r"^HAMLET",speech)
print("HAMLET" in match.group())
输出
真实的
此外,我们可以使用 regex 来查找两个字符之间的字符串。在下一个例子中,我们将使用 regex 模式来查找方括号中的字符串。
示例:查找两个特殊字符之间所有字符的正则表达式
speech="""KING CLAUDIUS
[Aside] O, 'tis too true!
How smart a lash that speech doth give my conscience!"""
match = re.search(r"(?<=\[).+?(?=\])",speech)
print(match.group())
输出
Aside
正则表达式包括许多元字符。涵盖所有这些超出了本教程的范围,但这里有一些以上的例子。
更多正则表达式元字符
- ****–用于转义特殊字符(例如, [ 字符)
- 。–通配符(匹配除换行符以外的任何字符)
- +–匹配多次出现
- ?–将前面的字符标记为可选
使用 Slice 对象分割字符串
Python slice 对象用于分割序列,如字符串或列表。slice 对象告诉 Python 如何对序列进行切片。
切片对象有三个参数:开始、停止和步进。前两个参数告诉 Python 从哪里开始和结束切片,而步骤参数描述了每个步骤之间的增量。
用一个切片对象我们可以得到字符之间的子串。要创建切片对象,使用切片()函数。该函数返回一个新的切片对象,该对象可以应用于字符串或其他序列。
示例:使用 Slice 对象获取子串
text="""To be, or not to be, that is the question,
Whether 'tis nobler in the mind to suffer"""
x = slice(19)
words = text[x]
print(words)
输出
To be, or not to be
摘要
本指南探讨了几种在字符之间拆分字符串的技术。这项任务最简单的解决方案通常是切片标记法,但这并不总是正确的。根据您的需要,可能需要使用其他 Python 方法来实现您的目标。
以下是我们所涉及主题的快速回顾:
- 使用 split()函数,我们可以将字符串分割成子字符串。
- 如果您需要非常有针对性的搜索,请尝试使用正则表达式。
- 切片对象是对字符串进行切片的另一种选择。
- 切片符号是一种在字符之间拆分字符串的快速方法。
您可以将每个选项视为 Python 开发人员工具箱中的一个工具。记住使用合适的工具来完成这项工作,你就会走上正轨。
相关职位
如果你觉得这个指南很有帮助,并且渴望学习更多的 Python 编程,请查看 Python 初学者的链接。
- 使用 Python 写文件保存文本文件
- 如何用字符串连接在 Python 中连接字符串
如何在 Python 中拆分字符串变量
原文:https://www.pythonforbeginners.com/basics/how-to-split-string-variables-in-python
在很多情况下,我们可能需要拆分字符串变量。在 python 中拆分字符串变量,我们可以使用带有不同参数的split()方法、rsplit()方法和splitlines()方法来完成不同的任务。在本文中,我们将探讨在 python 中拆分字符串变量的几种方法。
在空格处拆分字符串
要在每个空格处分割字符串变量,我们可以使用不带参数的split()函数。
split()函数的语法是split(separator, maxsplit),其中separator指定了字符串应该被拆分的字符。maxsplit指定字符串被拆分的次数。默认情况下,separator的值为whitespace,这意味着如果没有指定参数,字符串将在whitespaces处被拆分。参数maxsplit的默认值为-1,这表示字符串应该在所有separator出现时被拆分。
当我们在没有任何参数的情况下对任何字符串调用split()方法时,它将在每个有whitespace的地方执行 python 字符串拆分操作,并返回一个子字符串列表。
例子
myString="Python For Beginners"
print("The string is:")
print(myString)
myList=myString.split()
print("Output List is:")
print(myList)
输出:
The string is:
Python For Beginners
Output List is:
['Python', 'For', 'Beginners']
在任意特定字符处拆分字符串
要在 python 中以任何特定字符分割字符串变量,我们可以提供该字符作为分隔符参数。
例如,如果我们想在下划线_出现的地方拆分字符串Python_For_Beginners,我们将如下执行。
myString="Python_For_Beginners"
print("The string is:")
print(myString)
myList=myString.split("_")
print("Output List is:")
print(myList)
输出:
The string is:
Python_For_Beginners
Output List is:
['Python', 'For', 'Beginners']
在输出中可以看到,输出列表包含输入字符串的子字符串,这些子字符串在下划线字符处被拆分。
从左到右拆分字符串一定次数
如果我们想在指定字符的特定位置分割输入字符串,我们可以通过在split()方法中指定分割次数作为maxsplit参数来实现。这样,split()方法将把字符串从左到右拆分指定的次数。
下面的程序只在whitespace出现的地方分割字符串"Python For Beginners",如程序中的 python 注释所述。
#The string will be split at only one place where whitespace occurs.
myString="Python For Beginners"
print("The string is:")
print(myString)
myList=myString.split(maxsplit=1)
print("Output List is:")
print(myList)
输出:
The string is:
Python For Beginners
Output List is:
['Python', 'For Beginners']
在输出中可以看到,输入字符串仅在第一个whitespace处被拆分,输出列表仅包含两个子字符串。
在某个字符处从左到右将字符串变量拆分一定次数
如果我们想在指定字符的特定位置拆分输入字符串,我们可以通过指定字符串必须拆分的字符作为第一个参数,指定要拆分的数量作为maxsplit参数和 in split()方法来实现。
例如,如果我们想从左到右只在一个有下划线_的地方分割字符串Python_For_Beginners,我们可以这样做。
myString="Python_For_Beginners"
print("The string is:")
print(myString)
myList=myString.split("_",maxsplit=1)
print("Output List is:")
print(myList)
输出:
The string is:
Python_For_Beginners
Output List is:
['Python', 'For_Beginners']
在空格处从右向左拆分字符串变量一定次数
假设我们想从右到左拆分一个字符串一定的次数。为此我们可以使用rsplit()方法。
rsplit()函数的语法是rsplit(separator, maxsplit),其中separator指定了字符串应该被拆分的字符。maxsplit指定字符串被拆分的次数。默认情况下,separator的值为whitespace,这意味着如果没有指定参数,字符串将在whitespaces处被拆分。参数maxsplit的默认值为-1,这表示字符串应该在所有separator出现时被拆分。
为了从右到左在空格处分割字符串一定的次数,我们可以在maxsplit参数处指定字符串必须被分割的次数。
myString="Python For Beginners"
print("The string is:")
print(myString)
myList=myString.rsplit(maxsplit=1)
print("Output List is:")
print(myList)
输出:
The string is:
Python or Beginners
Output List is:
['Python For', 'Beginners']
在上面的输出中,我们可以看到字符串是从右向左拆分的,这与从左向右拆分字符串的split()方法不同。
在特定字符处从右向左拆分字符串变量一定次数
要在特定字符处从右到左拆分字符串一定次数,我们可以指定字符串必须拆分的字符作为 rsplit()方法的第一个参数。
例如,如果我们想从右到左只在一个有下划线_的地方分割字符串Python_For_Beginners,我们可以这样做。
myString="Python_For_Beginners"
print("The string is:")
print(myString)
myList=myString.rsplit("_",maxsplit=1)
print("Output List is:")
print(myList)
输出:
The string is:
Python_For_Beginners
Output List is:
['Python_For', 'Beginners']
在换行符或换行符处拆分字符串变量
要在换行符处拆分字符串变量,我们可以使用 python 中的splitlines()方法。当在任何字符串上调用时,它返回原始字符串的子字符串列表,原始字符串在换行符处被拆分以创建子字符串。
示例:
myString="Python is a good language.\n I love PythonForBeginners"
print("The string is:")
print(myString)
myList=myString.splitlines()
print("Output List is:")
print(myList)
输出:
The string is:
Python is a good language.
I love PythonForBeginners
Output List is:
['Python is a good language.', ' I love PythonForBeginners']
在输出中可以观察到,原始字符串包含两行文本,输出列表包含这两行作为其元素。
结论
在本文中,我们看到了使用split()、rsplit()和splitlines()方法在 python 中拆分字符串变量的各种方法。敬请关注更多文章。
如何在 Python 中接受用户输入
原文:https://www.pythonforbeginners.com/basics/how-to-take-user-input-in-python
在编程时,我们经常需要在程序中接受用户输入。在这篇文章中,我们将看看在 python 中获取用户输入的不同方法。我们将讨论将不同的 python 文字如字符串、整数和十进制值作为程序输入的方法。
如何在 Python 中获取输入
我们可以使用 input()方法获取 python 中的用户输入。
执行 input()方法时,它接受一个选项字符串参数,作为提示显示给用户。接受输入后,input()方法将用户输入的值作为字符串返回。即使用户输入一个数字或标点符号,input()方法也总是将输入作为字符串读取。您可以在下面的示例中观察到这一点。
value = input("Please input a number:")
print("The data type of {} is {}".format(value, type(value)))
输出:
Please input a number:1243
The data type of 1243 is <class 'str'>
在执行 input()方法时,程序的执行会暂停,直到用户输入后按下 enter 键。一旦用户按下 enter 键,input()方法就完成了它的执行。
如何在 Python 中接受整数输入
我们刚刚看到 input()方法将每个值都作为一个字符串读取。如果我们想验证用户输入了一个整数,我们可以使用正则表达式。
我们将使用 re.match()方法来验证给定的输入是否为整数。为此,我们将传递整数的正则表达式,即“[-+]?\d+$ "和输入字符串,以 re.match()方法作为输入。如果输入字符串包含除开头带有–或+符号的十进制数字以外的字符,re.match()方法将返回 None 。否则,match()方法返回一个 match 对象。要检查用户输入是否只包含整数,我们可以使用 re.match()方法,如下所示。
import re
flag = True
input_value = None
while flag:
input_value = input("Please input a number:")
match_val = re.match("[-+]?\\d+$", input_value)
if match_val is None:
print("Please enter a valid integer.")
else:
flag = False
number = int(input_value)
print("The input number is:", number)
输出:
Please input a number:Aditya
Please enter a valid integer.
Please input a number:PFB
Please enter a valid integer.
Please input a number:123.4
Please enter a valid integer.
Please input a number:+1234
The input number is: 1234
这里,我们使用了 while 循环反复提示用户输入整数。我们已经使用 re.match()方法检查了输入值。如果输入不正确,将再次执行 while 循环。否则,当标志变为假时,while 循环终止。类似地,我们可以使用下面讨论的 re.match()方法要求用户输入十进制数。
在 Python 中如何将十进制数作为输入
同样,我们将使用 re.match()方法来验证用户是否输入了有效的十进制数。为此,我们将传递十进制数的正则表达式,即“[-+]?\d+([/。]\d+)?$ "和 re.match()方法的输入字符串作为输入。如果输入字符串包含除十进制数字以外的字符,开头有–和+以及可选的小数点“.”在数字之间,re.match()方法将返回 None 。否则,match()方法返回一个 match 对象。要检查用户输入是否只包含一个十进制数,我们可以使用 re.match()方法,如下所示。
import re
flag = True
input_value = None
while flag:
input_value = input("Please input a number:")
match_val = re.match("[-+]?\\d+([/.]\\d+)?$", input_value)
if match_val is None:
print("Please enter a valid decimal number.")
else:
flag = False
number = float(input_value)
print("The input number is:", number)
输出:
Please input a number:Aditya
Please enter a valid decimal number.
Please input a number:PFB
Please enter a valid decimal number.
Please input a number:-123.456
The input number is: -123.456
结论
在本文中,我们看到了使用 input()方法在 python 中获取用户输入的各种方法。我们还讨论了使用 re.match()方法验证输入。要学习更多关于在 python 中验证字符串的知识,您可以阅读这篇关于 python 中的正则表达式的文章。
Python 中如何使用注释?
原文:https://www.pythonforbeginners.com/comments/how-to-use-comments-in-python
用 Python 写代码可能很有挑战性。这就是为什么在给变量和函数命名时,尽可能清晰是很重要的。一个好的名字会解释变量的用途,或者一个函数的作用。然而,好的命名约定只能让你到此为止。如果我们面对的是复杂的逻辑或令人困惑的算法呢?或者如果我们需要和另一个程序员分享和解释我们的意图呢?在代码中为自己或他人留下注释会很有帮助。这就是 Python 注释的用途。
有了注释,我们可以使我们的程序更容易理解,也更容易在以后进行修改。Python 注释会被解释器忽略,所以它们不会影响代码的运行。
我们将涉及的主题:
- 为什么写评论很重要
- 如何使用注释改进您的 Python 代码
- 用 Python 注释的最佳实践
什么时候写 Python 注释?
让我们面对现实吧,编程并不容易;我们都需要一些帮助。注释允许程序员添加一些额外的信息来解释代码中发生了什么。
如果你在做一个大项目,很难跟踪所有正在进行的事情。在长时间缺席后重返项目时尤其如此。
这种情况比你想象的更常见。程序员经常被要求同时处理许多项目。
回到一个项目往往是痛苦的。如果代码清晰,遵循样式指南,并利用恰当的注释,更新项目会容易得多。
当涉及到团队工作时,评论甚至更为重要。破译你自己的代码已经够难了,更别说是同事或陌生人写的了。遵循一些基本准则将有助于你写出清晰、有效的评论。
如何用 Python 写评论?
注释通常以块的形式编写,并解释其后的代码。通常,注释用于解释复杂的公式、算法或设计决策。
定义:注释是程序员可读的代码,被计算机忽略。这是给我们自己或其他从事项目的程序员的一个信息。
用法:使用注释来解释函数、算法、数学、设计选择或任何你将来可能需要参考的东西。
语法:Python 中的大多数注释都是使用 # 字符编写的。Python 在程序运行时会忽略任何跟在散列符号( #) 后面的代码。
Python 中有三种不同类型的注释:block、inline 和 docstring。知道何时使用每一种都很重要。例如,docstrings 可以用来自动生成项目的文档。
用 Python 编写单行注释
单行注释,在 Python 中称为块注释,以 # 字符开始。块注释用于解释注释后面的代码。
记住评论要尽可能的短。很容易做过头,在程序越多单词越清晰的印象下添加对所有事情的评论。那不是真的。
俗话说,简洁是智慧的灵魂。注释代码也是如此。保持简单是个好主意。
示例 1: Python 块注释
# this is a block comment in python, it uses a single line
# a list of keywords provided by the client
keywords = ["tv shows", "best streaming tv","hit new shows"]
例子 2:勾股定理
import math
# the sides of a triangle opposite the hypotenuse
a = 2
b = 3
# the Pythagorean Theorem
c = math.sqrt(a**2 + b**2)
print(c)
输出
3.605551275463989
行内注释
为了节省空间,有时把注释放在你描述的代码的同一行是个好主意。这就是所谓的内联注释。
行内注释也用 # 字符书写。它们被放在代码语句的末尾。当您想要包含有关变量名的更多信息,或者更详细地解释一个函数时,行内注释非常有用。
示例 3:用 Python 编写行内注释
income = 42765 # annual taxable income in USD
tax_rate = 0.22 # 22% annual tax rate
print("You owe ${}".format(income*tax_rate))
用 Python 编写多行注释
在 Python 中,编写超过一行的注释的最直接方法是使用多个块注释。Python 会忽略散列符号( #) ,留给你的是多行注释。
示例 4:多行注释
chessboard = {}
# we need to use a nested for loop to build a grid of tiles
# the grid of tiles will serve as a basis for the game board
# 0 will stand for an empty space
for i in range(1,9):
for j in range(1,9):
chessboard[i,y] = 0
不幸的是,使用这种方法需要在每行之前添加一个 hashtag。
虽然从技术上来说你不能写一个超过一行的注释,但是 Python docstrings 提供了一个绕过这个规则的方法。
文档字符串意味着与函数和类相关联。它们用于为您的项目创建文档,因为 docstring 将与它们所在的函数相关联。
文档字符串使用两组三重引号来表示它们之间的文本是特殊的。这些三重引号应该放在函数和类之后。它们用于记录 Python 代码。
示例 5:使用带有函数的 docstring
def string_reverse(a_string):
"""A helper function to reverse strings
Args:
a_string (sring):
Returns:
string: A reversed copy of the input string
"""
reverse = ""
i = len(a_string)
while i > 0:
reverse += a_string[i-1]
i = i-1
return reverse
# driver code
print(string_reverse("Is this how you turn a phrase?"))
输出
?esarhp a nrut uoy woh siht sI
我们还可以使用这些三重引号在 Python 中创建注释。因为它们是作为字符串读取的,所以运行时不会影响我们的程序。
""" this is a multiline comment in Python
it's basically just a string
but you have to be careful when using this method.
"""
建议阅读:要阅读更多计算机科学主题,您可以阅读这篇关于使用 ASP.net 的动态基于角色授权的文章。你也可以阅读这篇关于使用 Asp.net记录用户活动的文章。
为自己做评论
有些评论留给开发者自己。例如,你可以留下一个评论来提醒自己,你在之前的一个工作日没有完成的事情,你在哪里停下来了。
大型程序很难管理。当您打开一个项目时,尤其是如果它是您已经有一段时间没有查看的项目,您有时会发现您需要“重新加载”代码。本质上,你需要提醒自己该项目的细节。
在这方面,注释可以帮助节省时间。一些恰当的评论可以帮助你避免那些令人挠头的时刻,比如你问“我到底在这里做什么?”
为他人评论
无论何时你在一个团队中工作,无论是 Python 还是其他,交流都是至关重要的。这里的困惑只会导致浪费时间和沮丧。
这就是为什么程序员应该用注释来解释他们的代码。遵循风格指南并适当地评论你的作品将确保每个人都在同一页上。
如果你对机器学习感兴趣,你可以阅读这篇关于机器学习中回归的文章。您可能还会喜欢这篇关于使用 python 中的 sklearn 进行多项式回归的文章。
用 Python 注释的最佳实践
虽然 Python 注释通常使程序更容易理解,但情况并非总是如此。如果一个人希望写出富有成效的评论,他应该遵守一些不成文的规则。
的确,添加更多的注释并不一定能提高代码的可读性。事实上,评论太多和太少一样糟糕。那么你怎么知道评论多少,什么时候评论,或者什么时候不评论呢?
评论指南:
- 避免冗余
- 要尊重
- 少即是多
知道什么时候评论是不必要的是一项需要掌握的重要技能。通常,你会看到学生在变量中重复函数名,好像重新写一遍会让他们的意思更清楚。
不要做像这样不必要的评论:
# the name of the author
author_name = "Le Guin, Ursula K"
让我们看一个更长的例子,它有多个注释和一个 docstring。使用注释导航冒泡排序算法。
示例 7:注释冒泡排序算法
def BubbleSort(nums):
"""A method for quickly sorting small arrays."""
total_nums = len(nums)
for i in range(total_nums):
for j in range(0, total_nums-i-1):
# traverse the array backwards
# swap elements that are out of order
if nums[j] > nums[j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
nums = [100,7,19,83,63,97,1]
BubbleSort(nums)
print(nums)
输出
[1, 7, 19, 63, 83, 97, 100]
有用的链接
希望我已经给你留下了正确注释 Python 代码的重要性的印象。这会节省你的时间,使你的工作更容易。
想吃更多吗?通过点击这些链接到更多的 Python 初学者教程,提高你的 Python 编码技能。
如何在 Python 中使用 ConfigParser
原文:https://www.pythonforbeginners.com/code-snippets-source-code/how-to-use-configparser-in-python
什么是配置解析器?
Python 中的 configparser 模块用于处理配置文件。
它非常类似于 Windows INI 文件。
您可以使用它来管理用户可编辑的应用程序配置文件。
配置文件被组织成几个部分,每个部分可以包含配置数据的名称-值对。
通过查找以[开头并以]结尾的行来标识配置文件的节。
方括号之间的值是节名,可以包含除方括号之外的任何字符。
选项在一个部分中每行列出一个。
该行以选项的名称开始,用冒号(:)或等号(=)与值分隔。
解析文件时,分隔符周围的空格将被忽略。
包含“bug_tracker”部分和三个选项的示例配置文件如下所示:
[bug_tracker]
url = http://localhost:8080/bugs/
username = dhellmann
password = SECRET
常见用法
配置文件最常见的用途是让用户或系统管理员使用常规文本编辑器编辑文件,以设置应用程序行为默认值,然后让应用程序读取文件,解析它,并根据其内容进行操作。
MySQL 配置文件就是一个例子。
下面的脚本将读取/etc/mysql/debian.cnf 配置文件,以获取 mysql 的登录详细信息,连接到 MySQL 并向其请求所有数据库的列表,遍历该列表,对每个数据库调用 mysqldump。
这个脚本基于我在http://code poets . co . uk/2010/python-script-to-backup-MySQL-databases-on-debian/上找到的一段代码
备份所有 MySQL 数据库,每个文件一个,末尾有时间戳。
#Importing the modules
import os
import ConfigParser
import time
# On Debian, /etc/mysql/debian.cnf contains 'root' a like login and password.
config = ConfigParser.ConfigParser()
config.read("/etc/mysql/debian.cnf")
username = config.get('client', 'user')
password = config.get('client', 'password')
hostname = config.get('client', 'host')
filestamp = time.strftime('%Y-%m-%d')
# Get a list of databases with :
database_list_command="mysql -u %s -p%s -h %s --silent -N -e 'show databases'" % (username, password, hostname)
for database in os.popen(database_list_command).readlines():
database = database.strip()
if database == 'information_schema':
continue
if database == 'performance_schema':
continue
filename = "/backups/mysql/%s-%s.sql" % (database, filestamp)
os.popen("mysqldump --single-transaction -u %s -p%s -h %s -d %s | gzip -c > %s.gz" % (username, password, hostname, database, filename))
有关 ConfigParser 的更多信息,请参见以下链接:
http://www.doughellmann.com/PyMOTW/ConfigParser/
http://docs.python.org/2/library/configparser.html
Python 字典——如何用 Python 创建字典
原文:https://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python
Python 中的字典是无序的条目列表,可以通过使用内置方法进行更改。字典用于创建唯一键到值的映射。
关于 Python 中的字典
要创建字典,请使用{}花括号来构造字典,并使用[]方括号来索引它。
在每对之间,用冒号:和逗号分隔键和值。
必须引用关键字,例如:“title”:“如何在 Python 中使用字典”
与列表一样,我们可以通过打印词典的参考来打印出词典。
字典将一组对象(键)映射到另一组对象(值),因此您可以创建一个无序的对象列表。
字典是可变的,这意味着它们可以被改变。
键指向的值可以是任何 Python 值。
字典是无序的,所以添加键的顺序不一定反映它们被报告回来的顺序。因此,您可以通过值的键名来引用它。
创建新词典
为了构造一个字典,你可以从一个空的开始。
>>> mydict={}
这将创建一个字典,它最初有六个键-值对,其中 iphone*是键,年份是值
released = {
"iphone" : 2007,
"iphone 3G" : 2008,
"iphone 3GS" : 2009,
"iphone 4" : 2010,
"iphone 4S" : 2011,
"iphone 5" : 2012
}
print released
>>Output
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, '
iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}
向字典中添加值
您可以在下面的示例中向字典添加一个值。此外,我们将继续更改该值,以展示字典与 Python 集的不同之处。
#the syntax is: mydict[key] = "value"
released["iphone 5S"] = 2013
print released
>>Output
{'iphone 5S': 2013, 'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009,
'iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}
删除一个键及其值
您可以使用 del 运算符删除元素
del released["iphone"]
print released
>>output
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, 'iphone 5': 2012,
'iphone 4': 2010}
检查长度
len()函数给出字典中的对数。换句话说,字典里有多少个条目。
print len(released)
测试字典
使用 in 运算符检查给定字典中是否存在某个键,如下所示:
>>> my_dict = {'a' : 'one', 'b' : 'two'}
>>> 'a' in my_dict
True
>>> 'b' in my_dict
True
>>> 'c' in my_dict
False
或者像这样在 for 循环中
for item in released:
if "iphone 5" in released:
print "Key found"
break
else:
print "No keys found"
>>output
Key found
获取指定键的值
print released.get("iphone 3G", "none")
用 for 循环打印所有键
print "-" * 10
print "iphone releases so far: "
print "-" * 10
for release in released:
print release
>>output
----------
iphone releases so far:
----------
iphone 3G
iphone 4S
iphone 3GS
iphone
iphone 5
iphone 4
打印所有键和值
for key,val in released.items():
print key, "=>", val
>>output
iphone 3G => 2008
iphone 4S => 2011
iphone 3GS => 2009
iphone => 2007
iphone 5 => 2012
iphone 4 => 2010
仅从字典中获取键
phones = released.keys()
print phones
或者像这样打印出来:
print "This dictionary contains these keys: ", " ".join(released)
>>iphone 3G iphone 4S iphone 3GS iphone iphone 5 iphone 4
或者像这样:
print "This dictionary contains these keys: ", " ", released.keys()
>>['iphone 3G', 'iphone 4S', 'iphone 3GS', 'iphone', 'iphone 5', 'iphone 4']
打印值
元素可以通过方括号引用,例如:
print released[“iphone”]
print "Values:
",
for year in released:
releases= released[year]
print releases
>>output:
Values:
2008
2011
2009
2007
2012
2010
用 pprint 打印
pprint.pprint(released)
整理字典
除了打印之外,让我们对数据进行排序,以便得到预期的输出。
for key, value in sorted(released.items()):
print key, value
>>output:
('iphone', 2007)
('iphone 3G', 2008)
('iphone 3GS', 2009)
('iphone 4', 2010)
('iphone 4S', 2011)
('iphone 5', 2012)
"""
for phones in sorted(released, key=len):
print phones, released[phones]
>>output:
iphone 2007
iphone 5 2012
iphone 4 2010
iphone 3G 2008
iphone 4S 2011
iphone 3GS 2009
包括…在内
最后,让我们展示一下在字典中使用计数器来显示条目数量的价值。
count = {}
for element in released:
count[element] = count.get(element, 0) + 1
print count
>>output:
{'iphone 3G': 1, 'iphone 4S': 1, 'iphone 3GS': 1, 'iphone': 1,
'iphone 5': 1, 'iphone 4': 1}
如何在开发环境中使用 Fabric
概观
I earlier wrote a post on "How to use Fabric in Python", which can be found [here](../../../../systems-programming/how-to-use-fabric-in-python/ "fabric_usage").
I received a lot of responses from that article, so I decided to write another
post about Fabric. This time I would like to focus on how to use it in a
development environment.
什么是面料?
**Just to recap what Fabric is**
Fabric is a Python (2.5 or higher) library and command-line tool for streamlining
the use of SSH for application deployment or systems administration tasks.
It provides a basic suite of operations for executing local or remote shell
commands (normally or via sudo) and uploading/downloading files, as well as
auxiliary functionality such as prompting the running user for input, or aborting
execution.
为什么在开发环境中使用 Fabric?
So, we can use Fabric for streamlining the use of SSH for application deployment
or systems administration tasks.
In a development environment, where you have multiple servers with multiple people
pushing the code multiple times per day, this can be very useful.
If you would be the only person in the project who worked on a single server,
a git pull *(A git pull is what you would do to bring your repository up to date
with a remote repository)* and start working with it.
Often, you are not the only developer in a projet and there is where Fabric comes
into the picture. To avoid logging into multiple servers and running remote
commands, we can use Fabric to automate this whole process.
It can configure the system, execute commands on local/remote server, deploy your
application, do rollbacks etc. A common practice when developing is to use Git to
deploy and Fabric to automate it.
织物要求
An SSH server like OpenSSH needs to be installed on your server and an SSH client
needs to be installed on your client.
Fabric relies on the SSH Model, you can use SSH Keys but you can also control
access to root via sudoers.
The user on the server does not need to be added to "~/.ssh/authorized_keys",
but if it is you don't have to type the password every time you want to execute
a command.
If you ever have to disable the access to a user, just turn off their SSH account.
There is no transfer of code, so you only need to have ssh running on the remote
machine and have some sort of shell (bash is assumed by default).
织物安装
First off, we will have to install it, that can be done through pip
pip install fabric
Fabric 和 Fabfile.py
The installation added a Python script called **"fab"** to a directory in your path.
This is the **command** Fabric will use when it logs into one or more servers.
The **fabile.py** (see below) will be executed by the fab command.
All fabric does at its core is execute commands locally and remotely.
Fabric just provides a nice pythonic way of doing it.
The fabile is what Fabric uses to to **exectue task** and we need to specify which
shell commands we want Fabric to execute. In short, a fabfile is what controls
what Fabric executes.
The commands that we put into the fabfile will be executed on one or more hosts.
Every fabric scripts need to be in a file called fabfile.py. These hosts can be
defined either in the fabfile or on the command line.
All the functions defined in this file will show up as fab subcommands.
织物功能
Fabric provides a set of commands in **fabric.api** that are simple but powerful,
below are some of them
**local** # execute a local command)
**run** # execute a remote command on all specific hosts, user-level permissions)
**sudo** # sudo a command on the remote server)
**cd** # changes the directory on the serverside, use with the "with" statement)
**put** # uploads a local file to a remote server)
**get** # download a file from the remote server)
**prompt** # prompt user with text and return the input (like raw_input))
**reboot** # reboot the remote system, disconnect, and wait for wait seconds)
One of the most common Fabric functions is **run()**
It executes whatever command you put in as a parameter on the server.
Below you can see an example.
run("uptime")
This will run the uptime command on any server that we **specify** in the fabfile.py.
The server(s) are set using **env.hosts:**
env.hosts = ['[[email protected]](/cdn-cgi/l/email-protection)']
This tells the script to use the username **'superuser**' with the server address
**'host1.example.com'**
Basically, it's just like **ssh'ing** into a box and running the **commands** you've put
into run() and sudo(), but Fabric allows you to use several more **calls**.
设置开发环境
Before we start with creating Fabric functions, I want to show an example of how
a **directory structure** may look like:
$ mkdir /var/www/yourapplication
$ cd /var/www/yourapplication
$ virtualenv --distribute env
Before we can do anything, we first need to create a **fabile.py**.
If you are located in the same directory as "fabfile.py" you can go **"fab --list"**
to see a list of available commands and then **"fab [COMMAND_NAME]"** to execute a
command.
Now when everything is setup and we have an fabfile.py, let's put something in it.
Let's first start **defining roles** and then specify what action to do.
from fabric.api import *
# Define sets of servers as roles
env.roledefs = {
'www': ['www1', 'www2', 'www3', 'www4', 'www5'],
'databases': ['db1', 'db2']
}
# Set the user to use for ssh
env.user = 'fabuser'
# Restrict the function to the 'www' role (that we created above)
@roles('www')
def uptime():
run('uptime')
If we now want to see the uptime on all our web-servers, all we have to do is run:
$ fab -R www
# To run uptime on both roles (www and databases);
$ fab uptime
Any function you write in your fab script can be assigned to one or more roles.
You can also include a single server in multiple roles.
So this is nice, Fabric makes it really easy to run commands across sets of
machines.
使用结构进行部署
Let's see now how we can deploy something with Fabric. Often, we want to create
more than one function, depending on how your environment looks like (live,
staging, dev)
env.roledefs = {
'hostsDev': ['dev1', 'dev2'],
'hostsStaging':[ 'stg1', 'stg2'],
}
@roles('hostsDev')
def deploy_dev():
# Specify the path to where your codebase is located
path = "/home/fabuser/codebase"
# Get the code from Github
run ("git clone https://www.github.com/user/repo.git")
@roles('hostsStaging')
def deploy_staging():
# do something
If you now want to do a git clone to your development servers, all you need to do
is use the fab command:
**$ fab deploy_dev**
That's how you can create a deploy function using **Fabric**.
虚拟环境和要求
Now we have cloned our code from the Github repository. That is nice, but we can
do more, we can also install the requirements into a virtual environment.
For those of you that don't know what "requirements" is;
It's basically a file called **requirements.txt** which contain a list of packages
to install.
Instead of running something like pip install MyApp and getting whatever libraries
come along, you can create a requirements file that includes all dependencies.
Example of a requirements.txt file
BeautifulSoup==3.2.0
python-dateutil==1.4.1
django==1.3.0
django-debug-toolbar==0.8.5
django-tagging==0.3
Markdown==2.0.1
...
...
To install all packages that are in that file, simple type
pip install -r requirements.txt
A **virtual environment** can be created with **/bin/virtualenv 'app_name'** and
activated by typing **source /bin/activate**
使用 Fabric 从 requirements.txt 安装软件包
Having that information, let's create a Fabric script to install it.
# Import the module
from fabric.api import *
# Specify the user and host
env.hosts = ['[[email protected]](/cdn-cgi/l/email-protection)']
def deploy():
with cd("/home/fabuser/codebase/"):
run("git clone https://github.com/user/repo.git")
run("source /home/fabuser/codebase/venv/bin/activate && pip install -r /path/to/requirements.txt")
That small script will activate the virtual environment and install all packages
specified in the requirements.txt file.
Sample output
Downloading/unpacking BeautifulSoup==3.2.0 ....
Downloading BeautifulSoup-3.2.0.tar.gz
Running setup.py egg_info for package BeautifulSoup
...
...
...
Storing complete log in /home/fabuser/.pip/pip.log
使用 Fabric 重启 Apache 服务器
We can use Fabric for many other things, we can also create a Fabric script for
restarting our **Apache servers.**
That would look something like this
from fabric.api import *
env.hosts = ['[[email protected]](/cdn-cgi/l/email-protection):22']
def restart_apache2():
sudo('service apache2 restart')
To restart apache2 on host 'host1.example.com', the only thing we have to do is
$fab restart_apache2
使用结构发送电子邮件
We aren't limited to hosts in "roledefs", we could also for example put in email
addresses.
from fabric.api import env, run
# Define sets of email addresses as role
env.roledefs = {
'test': ['localhost'],
'dev': ['[[email protected]](/cdn-cgi/l/email-protection)'],
'staging': ['[[email protected]](/cdn-cgi/l/email-protection)'],
'production': ['[[email protected]](/cdn-cgi/l/email-protection)']
}
def deploy():
run('echo test')
To run it a specific role use the -R switch
$ fab -R test deploy
[localhost] Executing task 'deploy'
进一步阅读
[http://www.virtualenv.org/en/latest/](http://www.virtualenv.org/en/latest/ "virtualenv")
[http://www.pip-installer.org/en/latest/requirements.html](http://www.pip-installer.org/en/latest/requirements.html "requirements")
[http://docs.fabfile.org/en/1.6/](http://docs.fabfile.org/en/1.6/ "fabric")
[Stackoverflow](https://stackoverflow.com/questions/2326797/how-to-set-target-hosts-in-fabric-file "stackoverflow")
如何在 Python 中使用 Fabric
原文:https://www.pythonforbeginners.com/systems-programming/how-to-use-fabric-in-python
什么是面料?
Fabric is a Python library and command-line tool for streamlining the use of SSH
for application deployment or systems administration tasks.
Typical usage involves creating a Python module containing one or more functions,
then executing them via the fab command-line tool.
You can execute shell commands over SSH, so you only need to have SSH running on
the remote machine. It interact with the remote machines that you specify as if
they were local.
装置
Fabric requires Python version 2.5 or 2.6 (Fabric has not yet been tested on
Python 3.x)
The most common ways of installing Fabric is via, pip, easy_install or via
the operating system's package manager:
pip install fabric
sudo easy_install fabric
sudo apt-get install fabric # (the package is typically called fabric or python-fabric.)
Please read the [official](http://docs.fabfile.org/en/1.5/installation.html "fabfile") documentation for more information (dependancies etc..)
织物使用
On their [website](http://docs.fabfile.org/en/1.5/ "fabfile_doc") they write:
"it provides a basic suite of operations for executing local or remote shell
commands (normally or via sudo) and uploading/downloading files, as well as
auxiliary functionality such as prompting the running user for input, or
aborting execution"
Having that information, let's move on.
The installation process added a Python script called fab to a directory in
your path.
This is the script which will be used to make everything happen with Fabric.
Just running fab from the command-line won't do much at all.
In order to do anything interesting, we'll need to create our first fabfile.
Before we do that I would like to show some of the functions in Fabric.
织物功能
Fabric provides a set of commands in fabric.api that are simple but powerful.
With Fabric, you can use simple Fabric calls like
local # execute a local command)
run # execute a remote command on all specific hosts, user-level permissions)
sudo # sudo a command on the remote server)
put # copy over a local file to a remote destination)
get # download a file from the remote server)
prompt # prompt user with text and return the input (like raw_input))
reboot # reboot the remote system, disconnect, and wait for wait seconds)
证明
Fabric relies on the SSH Model, you can use SSH Keys but you can also control
access to root via sudoers.
The user on the server does not need to be added to "~/.ssh/authorized_keys",
but if it is you don't have to type the password every time you want to execute
a command.
If you ever have to disable the access to a user, just turn off their SSH account.
Fabfile
You can load Python modules with Fabric.
By default, it looks for something named either fabfile or fabfile.py.
This is the file that Fabric uses to execute tasks.
Each task is a simple function.
The fabfile should be in the same directory where you run the Fabric tool.
The fabfile is where all of your functions, roles, configurations, etc. will
be defined.
It's just a little bit of Python which tells Fabric exactly what it needs to do.
The "fabfile.py" file only has to be stored on your client.
An SSH server like OpenSSH needs to be installed on your server and an
SSH client needs to be installed on your client.
创建 Fabfile
To start just create a blank file called fabfile.py in the directory you’d like
to use the fabric commands from.
You basically write rules that do something and then you (can) specify on which
servers the rules will run on.
Fabric then logs into one or more servers in turn and executes the shell commands
defined in "fabfile.py".
If you are located in the same dir as "fabfile.py" you can go **"fab --list"**
to see a list of available commands and then "fab [COMMAND_NAME]" to execute a
command.
From [https://github.com/fabric/fabric](https://github.com/fabric/fabric "fabric_git")
Below is a small but complete "fabfile" containing a single task:
from fabric.api import run
def host_type():
run('uname -s')
Once a task is defined, it may be run on one or more servers, like so
**$ fab -H localhost,linuxbox host_type**
[localhost] run: uname -s
[localhost] out: Darwin
[linuxbox] run: uname -s
[linuxbox] out: Linux
Done.
Disconnecting from localhost... done.
Disconnecting from linuxbox... done.
You can run fab -h for a full list of command line options
In addition to use via the fab tool, Fabric's components may be imported into
other Python code, providing a Pythonic interface to the SSH protocol suite at
a higher level than that provided by e.g. the ssh library,
(which Fabric itself uses.)
连接到远程服务器
As you can see above, Fabric will look for the function host_type in the
fabfile.py of the current working directory.
In the next example we can see how the Fabric Api uses an internal env variable
to manage information for connecting to remote servers.
The user is the user name used to login remotely to the servers and the hosts is
a list of hosts to connect to.
Fabric will use these values to connect remotely for use with the run
and sudo commands.
It will prompt you for any passwords needed to execute commands or connect to
machines as this user.
# First we import the Fabric api
from fabric.api import *
# We can then specify host(s) and run the same commands across those systems
env.user = 'username'
env.hosts = ['serverX']
def uptime():
run("uptime")
This will first load the file ~/fabfile.py
Compiling the file into ~/fabfile.pyc # a standard pythonism
Connect via SSH to the host 'serverX'
Using the username 'username'
Show the output of running the command "uptime" upon that remote host.
Now, when we run the fabfile, we can see that we can connect to the remote server.
$ fab uptime
If you have different usernames on different hosts, you can use:
env.user = 'username'
env.hosts = ['[[email protected]](/cdn-cgi/l/email-protection)', 'serverX']
Now userX username would be used on 192.168.1.1 and 'username' would be used
on 'serverX'
角色
You can define roles in Fabric, and only run actions on servers tied to a
specific role.
This script will run get_version on hosts members of the role "webservers",
by running first on www1, then www2 etc.
fab -R webservers
from fabric.api import *
# Define sets of servers as roles
env.roledefs = {
'webservers': ['www1', 'www2', 'www3', 'www4', 'www5'],
'databases': ['db1', 'db2']
}
# Set the user to use for ssh
env.user = 'fabuser'
# Restrict the function to the 'webservers' role
@roles('webservers')
def get_version():
run('cat /etc/issue')
# To run get_version on both roles (webservers and databases);
$ fab get_version
@roles ('webservers', 'databases')
def get_version():
run('cat /etc/issue')
Any function you write in your fab script can be assigned to one or more roles.
You can also include a single server in multiple roles.
将目录复制到远程机器
I would like to end this introduction of Fabric, by showing an example of
how to copy a directory to a remote machine.
from fabric.api import *
env.hosts = ['[[email protected]](/cdn-cgi/l/email-protection)']
def copy():
# make sure the directory is there!
run('mkdir -p /home/userX/mynewfolder')
# our local 'localdirectory' (it may contain files or subdirectories)
put('localdirectory', '/home/userX/mynewfolder')
结论
Fabric can be used for many things, including deploying, restarting servers,
stopping and restarting processes.
You write the description of what is to be done in Python and Fabric takes
care of executing it on all the machines you specify.
Once you've used it a bunch of times you'll accumulate many "fab files" that
you can re-use.
Basically, any time we would need to log in to multiple servers to do something,
you can use Fabric.
It’s simple and powerful and the documentation is really good.
进一步阅读
[http://docs.fabfile.org/en/1.5/index.html](http://docs.fabfile.org/en/1.5/index.html "fabfile_official")
[https://gist.github.com/DavidWittman/1886632](https://gist.github.com/DavidWittman/1886632 "https://gist.github.com/DavidWittman/1886632")
[http://mattsnider.com/using-fabric-for-painless-scripting/](http://mattsnider.com/using-fabric-for-painless-scripting/ "http://mattsnider.com/using-fabric-for-painless-scripting/")
[http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip/](http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip/ "http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip/")
[http://code.mixpanel.com/2010/09/09/easy-python-deployment-with-fabric-and-git/](https://code.mixpanel.com/2010/09/09/easy-python-deployment-with-fabric-and-git/ "http://code.mixpanel.com/2010/09/09/easy-python-deployment-with-fabric-and-git/")
[http://stackoverflow.com/questions/6308686/understanding-fabric/9894988#9894988](https://stackoverflow.com/questions/6308686/understanding-fabric/9894988#9894988 "http://stackoverflow.com/questions/6308686/understanding-fabric/9894988#9894988")
如何在 Python 中使用 FTP
原文:https://www.pythonforbeginners.com/code-snippets-source-code/how-to-use-ftp-in-python
概观
本文将展示如何借助
ftplib 模块在 Python 中使用 FTP。
Ftplib
Python 中的 ftplib 模块允许您编写执行各种自动化 FTP 作业的 Python 程序。您可以轻松地连接到 FTP 服务器来检索
文件并在本地处理它们。
要在 Python 中使用 ftplib 模块,首先必须将其导入到脚本中。
打开连接
要“打开”到 FTP 服务器的连接,您必须创建对象。
一旦建立了连接(打开了),就可以使用 ftplib
模块中的方法。
有两种类型的方法:一种用于处理文本文件,另一种用于二进制文件。
您可以轻松浏览目录结构,管理和下载文件。
我如何使用它?
这个程序将首先连接到一个 ftp 服务器(ftp.cwi.nl ),然后使用 list()方法列出 FTP 服务器根目录中的
文件和目录。
from ftplib import FTP
ftp = FTP('ftp.cwi.nl') # connect to host, default port
ftp.login() # user anonymous, passwd [[email protected]](/cdn-cgi/l/email-protection)
ftp.retrlines('LIST') # list directory contents
我们的第二个程序打开一个到“ftp.sunet.se”的连接,用户名为“anonymous”
,电子邮件地址为“【受电子邮件保护】
然后使用 dir()
方法列出 FTP 服务器上的文件和目录。
输出保存到“文件”变量中。
然后,我使用打印来查看屏幕上的文件。
如果我想更改目录,我只需使用 ftp.cwd(path)即可。
要关闭 FTP 连接,请使用 quit()方法。
import ftplib
ftp = ftplib.FTP('ftp.sunet.se', 'anonymous', '[[email protected]](/cdn-cgi/l/email-protection)')
print "File List: "
files = ftp.dir()
print files
ftp.cwd("/pub/unix") #changing to /pub/unix
常见的 FTP 方法
FTP.connect(主机[,端口[,超时]])
连接到给定的主机和端口。
根据 FTP 协议规范的规定,默认端口号为 21。
很少需要指定不同的端口号。
对于每个实例,该函数只应调用一次
如果在创建实例时给定了主机,则根本不应该调用它。
所有其他方法只能在连接
完成后使用。
可选的超时参数以秒为单位指定连接
尝试的超时。
如果没有超时,将使用全局默认超时设置。
FTP.getwelcome()
返回服务器在回复初始连接时发送的欢迎消息。
此消息有时包含可能与用户相关的免责声明或帮助信息
FTP . log in([用户[,密码[,帐户]])
以给定用户的身份登录。
passwd 和 acct 参数是可选的,默认为空字符串。
如果未指定用户,则默认为“匿名”。
如果用户为“匿名”,默认密码为“【受电子邮件保护】”。
在连接
建立之后,对于每个实例,这个函数应该只调用一次。
如果在创建实例
时给定了主机和用户,则根本不应该调用它。
大多数 FTP 命令只有在客户端登录后才被允许。
acct 参数提供“会计信息”;很少有系统实现这一点。
FTP.retrbinary(命令,回调[,maxblocksize[,rest]])
以二进制传输模式检索文件。
命令应该是适当的 RETR 命令:“RETR 文件名”。
对于接收到的每个数据块调用回调函数,用一个单独的
字符串参数给出数据块。
可选的 maxblocksize 参数指定在为进行实际传输而创建的低级套接字对象上读取的最大块大小。
选择一个合理的默认值。rest 的含义与 transfercmd()
方法中的含义相同。
FTP.retrlines(命令[,回调])
以 ASCII 传输模式检索文件或目录列表。
命令应该是一个适当的 RETR 命令或命令,如名单,NLST 或
MLSD。
LIST 检索文件列表和关于这些文件的信息。
NLST 检索文件名列表。
在一些服务器上,MLSD 检索机器可读的文件列表和关于这些文件的信息。
回调函数是为每一行调用的,每一行都有一个包含
的字符串参数,即去掉了尾部 CRLF 的那一行。
默认回调将该行打印到 sys.stdout。
FTP.dir(argument[, …])
生成 LIST 命令返回的目录列表,并将其打印到
标准输出。
可选参数是要列出的目录(默认为当前服务器的
目录)。
可以使用多个参数将非标准选项传递给 LIST 命令。
如果最后一个参数是一个函数,就像对于
retrlines()一样作为回调函数使用;默认打印到 sys.stdout。
此方法返回 None。
FTP.delete(文件名)
从服务器上删除名为 filename 的文件。
如果成功,返回响应的文本,否则在出现
权限错误时引发 error_perm,在出现其他错误时引发 error_reply。
FTP.cwd(路径名)
在服务器上设置当前目录。
FTP.mkd(路径名)
在服务器上创建一个新目录。
FTP.pwd()
返回服务器上当前目录的路径名。
FTP.quit()
向服务器发送退出命令并关闭连接。
这是关闭连接的“礼貌”方式,但如果服务器对 QUIT 命令做出错误响应,可能会引发异常。
这意味着对 close()方法的调用,这使得 FTP 实例对后续调用无用。
FTP.close()
单方面关闭连接。
这不应应用于已经关闭的连接,例如在
成功调用 quit()之后。
在这个调用之后,FTP 实例不应该再被使用。
调用 close()或 quit()后,不能通过发出
另一个 login()方法来重新打开连接。
更多信息,请参见官方 Python 文档
如何使用枕头,PIL 的一把叉子
概观
在上一篇文章中,我写了关于 PIL,也称为 Python 图像库,这个库可以很容易地操作图像。自 2009 年以来,PIL 没有任何发展。因此,该网站的好心用户建议看一看枕头。这篇文章将告诉你如何使用枕头。
枕头是什么?
Pillow 是 PIL (Python Image Library)的一个分支,由 Alex Clark 和贡献者发起并维护。它以 PIL 法典为基础,然后演变成一个更好、更现代、更友好的 PIL 版本。它增加了对打开、操作和保存许多不同图像文件格式的支持。很多东西的工作方式和最初的 PIL 一样。
下载和安装枕头
在我们开始使用枕头之前,我们必须先下载并安装它。Pillow 适用于 Windows、Mac OS X 和 Linux。最新版本为“2.2.1”,受 python 2.6 及以上版本支持。要在 Windows 机器上安装 Pillow,您可以使用 easy_install:
easy_install Pillow
要在 Linux 机器上安装枕头,只需使用:
sudo pip install Pillow
要在 Mac OS X 上安装 Pillow,我必须先安装 XCode,然后通过自制软件安装先决条件。家酿安装后,我运行:
$ brew install libtiff libjpeg webp littlecms
$ sudo pip install Pillow
如果你知道在 Mac 上做这件事的更简单的方法,请告诉我。
验证枕头是否已安装
要验证 Pillow 是否已安装,请打开一个终端并键入以下内容:
$ python
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
如果系统返回“> > >”,则说明枕形模块安装正确。
文件格式
在我们开始使用 Pillow 模块之前,让我们提一下支持的一些文件类型。BMP EPS GIF IM JPEG MSP PCX PNG PPM TIFF WebP ICO PSD PDF 有些文件类型,你只有读取的可能,其他的你只能写入。要查看支持的文件类型的完整列表,以及关于它们的更多信息,请查看 Pillow 的手册。
如何使用枕头来处理图像
既然我们要处理图像,让我们先下载一个。如果您已经有一张图片可以使用,请跳过这一步。在我们的示例中,我们将使用名为“Lenna”或“Lena”的标准测试图像。该标准测试图像用于许多图像处理实验。就去这里下载图片。如果你点击图像,它会把它保存为 512×512 像素的图像。
使用枕头
让我们看看这个库的可能用途。基本功能可在图像模块中找到。您可以通过多种方式创建该类的实例:从文件中加载图像、处理其他图像或从头开始创建图像。导入您想要使用的枕头模块。
from PIL import Image
然后,您可以像往常一样访问功能,例如
myimage = Image.open(filename)
myimage.load()
加载图像
要从您的计算机中加载一个图像,您可以使用 use "open "方法来识别该文件,然后使用 myfile.load()加载所识别的文件。一旦图像被加载,你可以用它做很多事情。我经常在处理文件时使用 try/except 块。使用 try/except 加载我们的图像:
from PIL import Image, ImageFilter
try:
original = Image.open("Lenna.png")
except:
print "Unable to load image"
当我们使用 open()函数从磁盘读取文件时,我们不需要知道文件的格式。该库根据文件内容自动确定格式。现在,当您拥有一个图像对象时,您可以使用可用的属性来检查文件。例如,如果您想查看图像的大小,您可以调用“格式”属性。
print "The size of the Image is: "
print(original.format, original.size, original.mode)
“size”属性是一个包含宽度和高度(以像素为单位)的二元组。常见的“模式”是灰度图像的“L”,真彩色图像的“RGB”,以及印前图像的“CMYK”。上面的输出应该给你这个:
The size of the Image is:
('PNG', (512, 512), 'RGB')
模糊图像
这个例子将从硬盘上加载一个图像并模糊它。[ 来源
# Import the modules
from PIL import Image, ImageFilter
try:
# Load an image from the hard drive
original = Image.open("Lenna.png")
# Blur the image
blurred = original.filter(ImageFilter.BLUR)
# Display both images
original.show()
blurred.show()
# save the new image
blurred.save("blurred.png")
except:
print "Unable to load image"
To display the image, we used the "show()" methods. If you don't see anything, you could try installing ImageMagick first and run the example again.
创建缩略图
一个很常见的事情是为图像创建缩略图。缩略图是图片的缩小版本,但仍然包含图像的所有最重要的方面。
from PIL import Image
size = (128, 128)
saved = "lenna.jpeg"
try:
im = Image.open("Lenna.png")
except:
print "Unable to load image"
im.thumbnail(size)
im.save(saved)
im.show()
我们程序的结果,显示缩略图:
枕头中的过滤器
枕头模块提供以下一组预定义的图像增强过滤器:
BLUR
CONTOUR
DETAIL
EDGE_ENHANCE
EDGE_ENHANCE_MORE
EMBOSS
FIND_EDGES
SMOOTH
SMOOTH_MORE
SHARPEN
在我们今天的最后一个例子中,我们将展示如何将“轮廓”滤镜应用到图像中。下面的代码将获取我们的图像并应用
from PIL import Image, ImageFilter
im = Image.open("Lenna.png")
im = im.filter(ImageFilter.CONTOUR)
im.save("lenna" + ".jpg")
im.show()
我们应用了“轮廓”滤镜的图像:
我很喜欢试用枕头,以后我会写更多关于它的帖子。
更多阅读
http://pillow . readthe docs . org/en/latest/handbook/tutorial . html
如何使用 Pip 和 PyPI
原文:https://www.pythonforbeginners.com/basics/how-to-use-pip-and-pypi
pip–概述
pip 命令是一个安装和管理 Python 包的工具,比如那些在 Python 包索引中找到的
。
它是 easy_install 的替代品。
PIP 安装
安装 PIP 很容易,如果你运行的是 Linux,它通常已经安装好了。
如果它没有安装或者当前版本已经过时,你可以使用
包管理器来安装或更新它。
在 Debian 和 Ubuntu 上:
$ sudo apt-get install python-pip
关于 Fedora:
$ sudo yum install python-pip
如果您使用的是 Mac,只需通过 easy_install 安装即可:
sudo easy_install pip
PyPI——Python 包索引
现在,当 PIP 安装完成后,我们需要找到一个要安装的包。
包通常从 Python 包索引开始安装。
Python 包索引是 Python 编程语言
的软件仓库。
PIP 入门
现在,当我们知道 PIP 是什么并且已经安装在计算机上时,让我们看看如何使用它。
要安装 Python 包索引中的包,只需打开您的终端
并使用 PIP 工具输入搜索查询。
PIP–命令
只需在您的终端中键入 pip,您就会在
屏幕上看到以下输出:
用法:
pip <command> [options]
命令:
安装安装包。
卸载卸载包。
以需求格式冻结输出已安装的软件包。
list 列出已安装的软件包。
显示已安装软件包的信息。
search 搜索 PyPI 找包。
zip 拉链独立包装。
解压解压单个包。
bundle 创建 pybundles。
帮助显示命令的帮助。
pip 最常见的用法是安装、升级或卸载软件包。
PIP–搜索
要搜索一个包,比如 Flask,请键入以下内容:
pip search Flask
您应该看到一个输出,其中所有包都包含名称“Flask”和一个描述。
Flask-Cache–为您的 Flask 应用程序添加缓存支持。
Flask-Admin–Flask 的简单且可扩展的管理界面框架
Flask-Security–Flask 应用的简单安全性
Flask–基于 Werkzeug、Jinja2 和 good intentions 的微框架
pip–安装软件包
我们可以看到烧瓶是可用的。
flask——一个基于 Werkzeug、Jinja2 和善意的微框架让我们安装它吧
pip install Flask
pip–显示信息
Flask 已安装,让我们显示关于我们新安装的软件包的信息。
pip show Flask
—
名称:Flask
版本:0.10.1
位置:/usr/local/lib/python 2.7/dist-packages
要求:Werkzeug、Jinja2、itsdangerous
pip–卸载软件包
如果你想卸载一个由 PIP 安装的软件包,你也可以这样做。
pip uninstall Flask
Uninstalling Flask:
...
.....
Proceed (y/n)?
Successfully uninstalled Flask
使用 pip 很容易,有了它你可以很容易地从 Pypi 安装软件包。
更多阅读
https://pypi.python.org/pypi
http://www.pip-installer.org/en/latest/T5http://flask.pocoo.org/
如何使用 Python Split 函数
原文:https://www.pythonforbeginners.com/strings/how-to-use-python-split-function
Python 提供了一个用于拆分字符串的内置方法。使用 split() 函数,我们可以将单个字符串分解成一个字符串列表。
使用 split()是将大型字符串分解成更易于管理的部分的一种简单而有效的方法。
如果我们的任务是处理文本文件,这可能是一个有用的方法,我们将在后面看到。
Split 函数的定义和语法
split() 方法使用分隔符将字符串分隔成单个单词,也称为分隔符。Python 使用空白作为默认分隔符,但是您可以自由地提供一个替代符。
分隔符可以是任何东西,但通常是用来分隔字符串中单词的字符。例如,逗号通常用于拆分列表。
# the following string uses a comma as the separator.
groceries = “Bread,Milk,Eggs,Bananas,Coffee”
split()函数将返回一个字符串列表。默认情况下,对返回列表的长度没有限制。但是你可以用 maxsplit 设置来改变它。
语法:
my_string.split(separator,maxsplit)
分隔符:这是 Python 用来分割字符串的分隔符。如果没有提供分隔符,则使用空白作为分隔符。
maxsplit: 该设置用于决定字符串应该被拆分多少次。默认情况下,该列表没有限制。
为什么要在 Python 中使用 split()函数?
使用 split()函数有很多好的理由。无论是使用逗号分隔值(CSV)文件,还是试图将一个大字符串分解成小部分,split()都提供了一种在 Python 中分割字符串的有效方法。
split()函数将把一个字符串分解成单词列表。这些以 Python 字符串数组的形式返回给我们。下面是使用 split()的分步指南:
- 创建一个字符串。
- 使用 Python split()函数
- 打印结果
gandalf = "You shall not pass."
gandalf.split() # The string will be split based on whitespace.
这是我们分开绳子时的样子。
['You', 'shall', 'not', 'pass.']
使用 split() 函数和 python 字符串连接来快速连接和拆分字符串。split()函数对于快速解析逗号分隔值(CSV)文件也很有用。
Python 分割函数的示例
当我们使用 split()函数分割一个字符串时,Python 返回一个新的字符串数组。该数组保存拆分后的字符串。
比如说。如果我们有一个类似这样的字符串:
frosty_string = "Some say the world will end in fire."
我们可以看到字符串中的单词由空格分隔。用这个字符串运行 split()将返回一个新数组,其中包含罗伯特·弗罗斯特的一首著名诗歌的开头一行的单词。
示例 1:使用 Python split()和一个基本字符串
# this line is from Fire and Ice by Robert Frost
frosty_string = "Some say the world will end in fire."
words = frosty_string.split()
print(words)
输出
['Some', 'say', 'the', 'world', 'will', 'end', 'in', 'fire.']
还可以使用 split()将列表分成预定义数量的部分。正如我们在它的定义中看到的,split()函数有一个可选的第二个参数。通过设置 maxpslit ,我们可以告诉 Python 将列表分成两部分。
示例 2:使用 Python Split 将列表分成两部分
fruit = "Apples Oranges"
# setting maxsplit to 1 will return a list with 2 parts
two_max = fruit.split(' ', 1)
print(two_max)
输出
['Apples', 'Oranges']
使用逗号分割字符串数据
我们已经看到了 split()函数的基本用法。默认情况下,split()使用空格来分割字符串。虽然空格适用于某些数据,但其他字符通常更有意义。通常使用逗号来分隔字符串中的值。
使用逗号,我们可以很容易地快速拆分大量的字符串数据。在以下示例中,包含通用摇滚乐队中所有乐器的字符串被拆分为一个新列表。
示例 3:使用逗号作为分隔符
# use a comma as the separator
band = "Guitar,Piano,Drums,Trumpet,Bass Guitar,Vocals"
instruments = band.split(',')
print(instruments)
输出
['Guitar', 'Piano', 'Drums', 'Trumpet', 'Bass Guitar', 'Vocals']
使用逗号作为分隔符可以很容易地将字符串转换成列表。将字符串转换成列表(反之亦然)是一种存储和读取数据的便捷方法。
用 Split()函数读取文本文件
我在电脑上创建了一个名为 chess.txt 的文本文件。该文件与我的 Python 文件位于同一文件夹中。
这个文本文件包含一行,列出了国际象棋游戏中使用的棋子。请注意,逗号用于分隔各部分的名称。
国王、王后、车、骑士、主教、棋子
利用 split(),我们可以很容易地将游戏棋子分开。我们将使用 Python 的 open() 方法来读取文件,并在分割字符串之前提取文本行。
示例 4:使用 split()分隔文本文件中的单词
file = open("chess.txt")
pieces = file.read().split(',')
print(pieces)
输出
['King', 'Queen', 'Rook', 'Knight', 'Bishop', 'Pawn\n']
将 Strip()与 Split()函数一起使用
回头看看上一个例子,您可能会注意到我们的列表有些奇怪。我们在某个地方发现了一些迷失的角色。那个 \n 是哪里来的?
这是新的行字符。它告诉 Python 我们已经到达了文本文件的行尾。
我们可以利用 Python 的 strip() 方法把新的行字符从我们的列表末尾去掉。使用这种方法将确保我们不会从文件中提取任何讨厌的隐藏字符,例如 \n 字符。
file = open("chess.txt")
pieces = file.read().strip().split(',')
print(pieces)
file.close()
输出
['King', 'Queen', 'Rook', 'Knight', 'Bishop', 'Pawn']
拆分多行文本
上面的例子是相对基础的。毕竟,我们只有一行文本要处理。但是如果我们有用逗号分隔的数据行呢?让我们看看读取一个简单的数据库可能是什么样子。
我们将为一位需要计算班上每个学生平均成绩的老师编写一个程序。
我们的客户需要跟踪他/她的学生的作业。具体来说,他/她想要一种读取存储在文本文件中的数据的方法。这个名为 grades.txt 的文件包含了老师的学生的成绩。
我们的 teachers_pet.py 程序将从一个文件中读取信息,并构建一个包含成绩数据的字符串。
一旦我们有了成绩字符串,我们就可以使用 split()函数来拆分成绩并将它们存储在一个列表中。之后,我们需要使用 float() 方法将字符串转换成数字。
虽然这确实是一个复杂的过程,但是这个例子展示了在 Python 中处理数字和字符串的各种方法。
grades.txt
诺亚 81、94、100、65
伊利亚 80、84、72、79
卢卡斯 95、80、89、89
艾玛 95、80、80、80、77
艾娃 90、84、85、80
阿米莉亚 100、100、95、0
例 5:教师的宠物项目
# teachers_pet.py
file = open("grades.txt", 'r')
grade_data = []
while(True):
line = file.readline()
if not line:
break
grade_data.append(line.split(','))
print(grade_data)
file.close()
# this function will loop through the student's grades
def calculate_averages(grades_data):
for grades in grade_data:
total = 0
# the student's name occupies the first spot
for i in range(1,len(grades)):
total += float(grades[i].strip()))
avg = total/float(len(grades)-1)
print("{} has an average of {}.".format(grades[0],avg))
calculate_averages(grade_data)
输出
Noah has an average of 85.0
Elijah has an average of 78.75
Lucas has an average of 88.25
Emma has an average of 83.0
Ava has an average of 84.75
Amelia has an average of 73.75
我们的节目有两部分。在第一部分中,我们用 open()方法从文件中读取数据。一行一行地,每个学生的成绩被添加到一个名为 grades_data 的列表中。
我们利用 float() 将字符串转换成数字。我们还将使用 strip() 删除任何不必要的字符,例如 \n 字符。
请记住,成绩列表中的第一个元素是学生的姓名。
我们还需要一个函数来计算和打印成绩平均值。我们在calculation _ averages()中这样做。这个方便的功能将查看成绩数据,并找到每个学生的平均绩点。
进一步研究的教训
Python 附带了许多可以改进代码的内置函数。split()函数就是这样一个工具,可以用来分解困难的字符串问题。
使用分隔符分隔字符串允许您将字符串数据转换为字符串列表,这样更易于管理。split()函数也是一种快速分解从文件中读取的文本数据的方法。
通过访问以下教程,了解关于 Python 以及如何提高编程技能的更多信息。
如何使用 Python virtualenv
原文:https://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv
什么是 Virtualenv?
简而言之,虚拟环境是 Python 的一个独立的工作副本,它允许你在一个特定的项目上工作,而不用担心影响其他项目
它支持多个并行的 Python 安装,每个项目一个。
它实际上并没有安装单独的 Python 副本,但是它确实提供了一种
聪明的方法来隔离不同的项目环境。
验证是否安装了 Virtualenv
您的系统上可能已经安装了 virtualenv。
在您的终端中运行以下命令
virtualenv --version
如果您看到一个版本号(在我的例子中是 1.6.1),那么它已经安装好了。
T2>1 . 6 . 1
安装虚拟
有多种方法可以在您的系统上安装 virtualenv。
$ sudo apt-get install python-virtualenv
$ sudo easy_install virtualenv
$ sudo pip install virtualenv
设置和使用 Virtualenv
一旦安装了 virtualenv,只需启动一个 shell 并创建自己的
环境。
首先为您新的闪亮的隔离环境创建一个目录
mkdir ~/virtualenvironment
要为您的新应用程序创建一个包含 Python 的干净副本的文件夹,
只需运行:
virtualenv ~/virtualenvironment/my_new_app
(如果您想将您的环境与主站点
软件包目录隔离,请添加–无站点软件包)
要开始使用您的项目,您必须 cd 进入您的目录(project)
并激活虚拟环境。
cd ~/virtualenvironment/my_new_app/bin
最后,激活您的环境:
source activate
请注意您的 shell 提示符是如何改变的,以显示活动环境。
这就是你如何看到你在你的新环境中。
您现在使用 pip 或 easy_install 安装的任何软件包都会被安装到
my _ new _ app/lib/python 2.7/site-packages 中。
要退出 virtualenv,只需输入“停用”。
Virtualenv 做了什么?
这里安装的包不会影响全局 Python 安装。
Virtualenv 不会创建获得全新 python 环境所需的每个文件
它使用全局环境文件的链接,以节省磁盘空间并加速你的虚拟化。
因此,您的
系统上必须已经安装了一个活动的 python 环境。
在您的虚拟机中安装软件包
如果您查看 virtualenv 中的 bin 目录,您会看到 easy_install,其中的
已经被修改,可以将 eggs 和包放在 virtualenv 的 site-packages
目录中。
要在虚拟机中安装应用程序,请执行以下操作:
pip install flask
您不必使用 sudo,因为这些文件将全部安装在 virtualenv
/lib/python 2.7/site-packages 目录中,该目录是作为您自己的用户帐户创建的
就这样,我希望你能从这篇文章中学到一些东西
进一步阅读请见:
http://flask.pocoo.org/docs/installation/#virtualenv
http://pypi.python.org/pypi/virtualenv
入门-虚拟-隔离-python-environments/
如何在 Python 中使用 Reddit API
原文:https://www.pythonforbeginners.com/api/how-to-use-reddit-api-in-python
Reddit API–概述
在早先的一篇文章“如何用 Python 访问各种 Web 服务”中,我们描述了
如何通过 API 访问 YouTube、Vimeo 和 Twitter 等服务。
注意,有几个 Reddit 包装器可以用来与 Reddit 交互。
包装器是一个 API 客户端,通常用于通过调用 API 本身将 API 包装成易于使用的函数。
这导致它的用户不太关心代码
实际上是如何工作的。
如果你不使用包装器,你将不得不直接访问 Reddits API,
这正是我们在本文中要做的。
入门指南
既然我们要关注 Reddit 的 API,那就让我们去看看他们的 API
文档。我建议你熟悉文档,并且
额外注意概述和关于“模式哈希”、“T4”、“全名”和“类型前缀”的章节。
API 的结果将作为 XML 或 JSON 返回。在这篇文章中,我们将使用 JSON 格式。
关于 JSON 结构的更多信息
,请参考上面的帖子或者官方文档。
API 文档
在 API 文档中,您可以看到有大量的事情要做。
在这篇文章中,我们选择从我们自己的 Reddit 帐户中提取信息。
我们需要的信息是: GET /user/username/where[。json |。xml ]
获取/用户/用户名/where[。json |。xml ]
?/用户/用户名/概述
?/用户/用户名/提交的
?/用户/用户名/评论
?/用户/用户名/喜欢的
?/用户/用户名/不喜欢的
?/用户/用户名/隐藏
?/用户/用户名/已保存
查看 JSON 输出
例如,如果我们想使用“评论”,URL 将是:
【http://www.reddit.com/user/spilcm/comments/.json】
您可以看到,我们已经用自己的输入替换了“用户名”和“位置”。
要查看数据响应,您可以发出一个 curl 请求,如下所示:
curl http://www.reddit.com/user/spilcm/comments/.json
…或者只需将 URL 粘贴到您的浏览器中。
可以看到响应是 JSON。这可能很难在
浏览器中看到,除非你安装了 JSONView 插件。
开始编码
现在我们有了 URL,让我们开始做一些编码。
打开你最喜欢的空闲/编辑器,导入我们需要的模块。
导入模块。pprint 和 json 模块是可选的。
from pprint import pprint
import requests
import json
进行 API 调用
现在是时候对 Reddit 进行 API 调用了。
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
现在,我们有一个名为“r”的响应对象。我们可以从这个物体中获得我们需要的所有信息。
JSON 响应内容
Requests 模块带有一个内置的 JSON 解码器,我们可以用它来处理 JSON 数据。
正如你在上面的图片中看到的,我们得到的输出并不是我们真正想要显示的。
问题是,我们如何从中提取有用的数据?
如果我们只想查看“r”对象中的键:
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
data = r.json()
print data.keys()
这将为我们提供以下输出:
[u'kind ',u'data']
这些钥匙对我们来说非常重要。
现在是获取我们感兴趣的数据的时候了。
获取 JSON 提要并将输出复制/粘贴到 JSON 编辑器中,以便更容易地查看数据。
一种简单的方法是将 JSON 结果粘贴到在线 JSON 编辑器中。
我使用http://jsoneditoronline.org/,但是任何 JSON 编辑器都应该做这项工作。
让我们来看一个例子:
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
r.text
从图中可以看出,我们得到了与之前
打印密钥时相同的密钥(种类、数据)。
将 JSON 转换成字典
让我们将 JSON 数据转换成 Python 字典。
你可以这样做:
r.json()
#OR
json.loads(r.text)
现在,当我们有了一个 Python 字典,我们开始使用它来获得我们想要的结果。
导航以查找有用的数据
沿着你的路往下走,直到你找到你想要的。
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
r.text
data = r.json()
print data['data']['children'][0]
结果存储在变量“数据”中。
为了访问我们的 JSON 数据,我们简单地使用括号符号,就像这样:
data['key']。
记住数组是从零开始索引的。
我们可以使用 for 循环遍历字典,而不是打印每一个条目。
for child in data['data']['children']:
print child['data']['id'], "
", child['data']['author'],child['data']['body']
print
我们可以像这样访问任何我们想要的东西,只要查找你感兴趣的数据。
完整的剧本
正如您在我们完整的脚本中看到的,我们只需要导入一个模块:
(请求)
import requests
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
r.text
data = r.json()
for child in data['data']['children']:
print child['data']['id'], "
", child['data']['author'],child['data']['body']
print
当您运行该脚本时,您应该会看到类似如下的内容:
更多阅读
http://docs.python-requests.org/en/latest/
如何在 Python 中使用 sh
原文:https://www.pythonforbeginners.com/modules-in-python/how-to-use-sh-in-python
什么是 sh?
sh 是一个独特的子进程包装器,它将你的系统程序动态映射到 Python
函数。 sh 通过给你
Bash 的良好特性(简单的命令调用,简单的管道)和 Python 的所有功能
和灵活性,帮助你用 Python 编写 shell 脚本。[ 来源 ]
从 sh 开始
sh 是一个成熟的 Python 子进程接口,允许你调用任何 T2 程序,就像调用一个函数一样。与使用子进程相比,sh 可以让你调用任何你
可以从登录 shell 中运行的东西。更重要的是,可以让您更容易地捕获和解析输出。
装置
sh 的安装通过 pip 命令完成
pip install sh
使用
最简单的方法是直接导入 sh 或者从 sh 导入你的
程序。您想要运行的每个命令都像任何其他模块一样被导入。
该命令就像 Python 语句一样可用。
参数通常被传递,输出可以以类似于
的方式被捕获和处理。
# get interface information
import sh
print sh.ifconfig("eth0")
from sh import ifconfig
print ifconfig("eth0")
# print the contents of this directory
print ls("-l")
# substitute the dash for an underscore for commands that have dashes in their names
sh.google_chrome("http://google.com”)
使用 sh 执行命令
命令就像函数一样被调用。
"注意,这些不是 Python 函数,它们通过解析路径在系统上动态运行二进制命令
,就像 Bash 所做的那样。通过这种
方式,你系统上的所有程序都可以很容易地用 Python 实现。”
许多程序都有自己的命令子集,比如 git (branch,checkout)。
sh 通过属性访问处理子命令。
from sh import git
# resolves to "git branch -v"
print(git.branch("-v"))
print(git("branch", "-v")) # the same command
关键字参数
关键字参数也像您预期的那样工作:它们被替换为
长格式和短格式命令行选项。来源
# Resolves to "curl http://duckduckgo.com/ -o page.html --silent"
sh.curl("http://duckduckgo.com/", o="page.html", silent=True)
# If you prefer not to use keyword arguments, this does the same thing
sh.curl("http://duckduckgo.com/", "-o", "page.html", "--silent")
# Resolves to "adduser amoffat --system --shell=/bin/bash --no-create-home"
sh.adduser("amoffat", system=True, shell="/bin/bash", no_create_home=True)
# or
sh.adduser("amoffat", "--system", "--shell", "/bin/bash", "--no-create-home”)
查找命令
“Which”查找程序的完整路径,如果不存在,则返回 None。
这个命令是作为 Python 函数实现的少数命令之一,因此
不依赖于实际存在的“哪个”程序。
print sh.which("python") # "/usr/bin/python"
print sh.which("ls") # "/bin/ls"
if not sh.which("supervisorctl"): sh.apt_get("install", "supervisor", “-y”)
你可以在 sh 上使用更多的特性,你可以在官方文档中找到所有的
。
烘烤
sh 能够将参数“烘焙”成命令。
# The idea here is that now every call to ls will have the “-la” arguments already specified.
from sh import ls
ls = ls.bake("-la")
print(ls) # "/usr/bin/ls -la"
# resolves to "ls -la /"
print(ls(“/“))
烘焙的 ssh 命令
在命令上调用“bake”会创建一个可调用的对象,该对象会自动传递
以及传递给“bake”的所有参数。
# Without baking, calling uptime on a server would be a lot to type out:
serverX = ssh("myserver.com", "-p 1393", "whoami")
# To bake the common parameters into the ssh command
myserver = sh.ssh.bake("myserver.com", p=1393)
print(myserver) # "/usr/bin/ssh myserver.com -p 1393”
既然“myserver”可调用对象代表了一个烘焙的 ssh 命令,那么您可以轻松地调用服务器上的任何内容:
# resolves to "/usr/bin/ssh myserver.com -p 1393 tail /var/log/dumb_daemon.log -n 100"
print(myserver.tail("/var/log/dumb_daemon.log", n=100))
# check the uptime
print myserver.uptime()
15:09:03 up 61 days, 22:56, 0 users, load average: 0.12, 0.13, 0.05
更多高级功能,请参见官方文档。
来源
https://github.com/amoffat/sh
https://github.com/Byzantium/Byzantium
如何使用 Python SimpleHTTPServer
原文:https://www.pythonforbeginners.com/modules-in-python/how-to-use-simplehttpserver
Python 为我们提供了各种模块来完成不同的任务。如果想用 Python 创建一个简单的 web 服务器来服务文件,可以使用 Python SimpleHTTPServer 模块。在本文中,我们将讨论 Python SimpleHTTPServer 的基础知识及其工作原理。
什么是 Python SimpleHTTPServer?
Python 附带的 SimpleHTTPServer 模块是一个简单的 HTTP 服务器,
提供标准的 GET 和 HEAD 请求处理程序。您可以轻松地在 localhost 上设置一个服务器来提供文件服务。您还可以使用 SimpleHTTPServer 模块编写 HTML 文件并在 localhost 上创建一个工作的 web 应用程序。
为什么应该使用 Python SimpleHTTPServer?
内置 HTTP 服务器的一个优点是您不需要安装和配置任何东西。你唯一需要的就是安装 Python。当您需要一个快速运行的 web 服务器,并且不想设置 apache 或类似 Ngnix 的服务器时,这是一个完美的选择。
SimpleHTTPServer 是一个简单而高效的工具,它使用 GET 请求和 POST 请求来了解服务器或 web 应用程序是如何工作的。您可以使用它将系统中的任何目录转换成您的 web 服务器目录。
如何使用 Python SimpleHTTPServer?
要在端口 8000(默认端口)上启动 HTTP 服务器,只需键入:
python -m SimpleHTTPServer [port]
上述命令适用于 Python 2。要在 Python 3 中运行 SimpleHTTPServer,需要执行以下命令。
python -m http.server [port]
执行上述命令后,您可以在 web 浏览器中打开链接 localhost:8000。在那里,您将找到启动 SimpleHTTPServer 的目录中的所有文件。您可以单击任何文件或目录,向服务器发送 GET 请求来访问这些文件。
您也可以将端口更改为其他名称:
$ python -m SimpleHTTPServer 8080
执行上述命令后,Python SimpleHTTPServer 将在端口 8080 上运行,而不是在端口默认端口上运行。
建议阅读:要了解如何使用 SimpleHTTPServer 编写 python 程序来服务带有自定义路径的文件,可以阅读这篇关于带有默认和自定义路径的 simple http server的文章。
如何共享文件和目录?
使用 SimpleHTTPServer 共享文件和目录。您首先需要移动到您想要共享其内容的目录。为此,您可以打开一个终端和 cd,进入您希望通过浏览器和 HTTP 访问的任何目录。之后,就可以启动服务器了。
cd /var/www/
$ python -m SimpleHTTPServer
按 enter 键后,您应该会看到以下消息:
在 0.0.0.0 端口 8000 上提供 HTTP 服务…
然后,您可以打开您最喜欢的浏览器,输入以下任何一个地址:
http://your_ip_address:8000
http://127.0.0.1:8000
如果目录中没有 index.html 文件,那么所有文件和目录都会列出来。
只要 HTTP 服务器在运行,终端就会随着从 Python web 服务器加载数据而更新。您应该看到标准的 http 日志记录信息(GET 和 PUSH)、404 错误、IP 地址、日期、时间以及所有您希望从标准 HTTP 日志中看到的信息,就好像您正在跟踪 apache access 日志文件一样。
SimpleHTTPServer 是从命令行提供当前目录内容的好方法。虽然有很多 web 服务器软件(Apache、Nginx),但是使用 Python
内置的 HTTP server 不需要安装和配置。
结论
在本文中,我们讨论了 Python SimpleHTTPServer 的基础知识。要了解更多关于 python 编程的知识,您可以阅读这篇关于 python 中的字符串操作的文章。你可能也会喜欢这篇关于用 Python 理解列表的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
如何在 Python 中使用 sys.arv
原文:https://www.pythonforbeginners.com/argv/how-to-use-sys-arv-in-python
刚接触 Python 的学生很早就学会了如何使用 input() 接受来自用户的数据。然而,还有另一种与程序交互的方法。
使用 sys 模块,可以直接从命令提示符或终端向 Python 程序传递参数。
这个特性允许在编写和运行程序时有更大的灵活性。例如,通过向 Python 程序提供不同的参数,可以改变代码的行为。
我们可以告诉 Python 程序根据通过命令行传递的参数来执行不同的功能。
sys.argv 是什么?
sys 模块让我们影响 Python 解释器的行为。使用 sys.argv,Python 将在命令行中查找参数,并将它们作为列表提供给我们的程序。
这意味着我们可以在用户运行程序时寻找用户提供的输入。然后,我们可以使用该信息来更改输出。
我如何使用它?
在使用 sys 模块之前,您需要导入它。我们可以用 import 关键字,后跟模块名来实现。
导入语法:
import *module_name*
有大量的 Python 库可供选择。熟悉 sys 之类的常用模块是个不错的主意。
示例 1:导入 sys 模块
import sys
print(sys.version)
运行这段代码将告诉您正在使用的 Python 版本,以及关于您的计算机系统的一些其他相关信息。
通过 sys 模块,我们可以操纵 Python 运行时环境。例如,我们可以从命令行改变与 Python 交互的方式。
命令行参数简介
sys 模块让我们从命令行向 python 提供额外的参数。这些参数作为列表包含在内。它们可以用来从命令行改变程序的行为方式。
这些附加参数位于 python 文件的名称之后。以下是在 Python 中使用命令行参数的语法:
python python_file.py arg1 arg2 arg3
在下面的例子中,我们将传递三个参数。使用 len() 方法,我们可以找到并显示 sys.argv 列表的长度。
示例 2:使用 sys.argv
# use len() to find the number of arguments passed to Python
import sys
total_args = len(sys.argv)
print("You passed: {} arguments.".format(total_args))
print("First argument: {}".format(sys.argv[0]))
在命令提示符中,键入“python”和文件名后,包括一些附加参数,如下所示:
投入
python pfb_args.py one two three
输出
You passed: 4 arguments.
First argument: argv.py
如您所见,Python 将文件名作为第一个参数。其他参数按照给出的顺序排列。
默认情况下, len() 方法在参数列表中包含文件名。如果我们想知道传递的参数的数量并且不包括文件名,我们可以使用 len(sys.argv)-1 。
import sys
# exclude the file name from the list of arguments
total_args = len(sys.argv)-1
print("You passed: {} arguments.".format(total_args))
投入
python pfb_args.py one two
输出
You passed: 2 arguments.
打印 sys.argv 中的所有元素
因为命令行参数是作为列表传递的,所以我们可以用 for 循环遍历它们。
示例 3:使用 for 循环打印 sys.argv
import sys
total_args = len(sys.argv)
for i in range(total_args):
print("First argument: {}".format(sys.argv[i]))
投入
python pfb_args.py one two three
输出
First argument: argv.py
First argument: one
First argument: two
First argument: three
使用 str()方法打印 sys.argv
然而,有一种更简单的方法来打印 sys.argv 的内容。 str() 方法让我们将 sys.argv 的内容打印为一个字符串。
示例 5:对 sys.argv 使用 str()方法
import sys
print(str(sys.argv))
在命令提示符下:
python pfb_args.py one two three
输出
['argv.py', 'one', 'two', 'three']
用 sys.argv 求一个数的幂
我们可以在终端使用命令行参数来计算一个数的幂。
在对输入执行任何计算之前,我们需要转换参数。默认情况下,Python 假设我们正在传递字符串。
要将字符串转换成数字,使用 int() 方法。在下面的例子中, int() 方法用于将用户输入转换成数字。
在 Python 中, ****** 运算符用于计算给定数字的幂。
示例 6:寻找能力
number = int(sys.argv[1])
power = int(sys.argv[2])
print("{} to the power of {} is {}.".format(number, power, number**power))
投入
python pfb_args.py 9 2
输出
9 to the power of 2 is 81.
求一组的平均值
再比如,我们可以用 sys.argv 来求一组数字的平均值。我们将使用一个 python string split 方法从列表中删除第一个元素。请记住,sys.argv 列表中的第一个元素将是 python 文件的名称。我们想忽略这一点。
从命令行传递给 Python 的任何参数都将被读取为字符串。我们必须使用 float() 将它们转换成浮点数。
得到总和后,我们需要用它除以集合的长度。确定传递了多少个数字的一种方法是从 sys.argv 的长度中减去 1。
示例 7:使用 sys.argv 查找一组数字的平均值
# find the average of a set of numbers
import sys
nums = sys.argv[1:]
sum = 0
for num in nums:
sum += float(num)
average = sum/(len(sys.argv)-1)
print("The average of the set is: {}".format(average))
投入
python sum_of_set.py 5 100 14 25
输出
The average of the set is: 36.0
使用 sys.argv 读取文件
sys 模块通常用于处理多个文件。例如,如果我们编写一个 Python 程序来编辑文本文件,如果有一种方法可以轻松地告诉程序要读取什么文件,这将是非常有用的。
根据我们已经了解的 sys 模块和命令行参数的信息,我们可以告诉 Python 读取文本文件。此外,我们可以一次提供几个文件,Python 会读取所有文件。
在下一个示例中,我们将使用 sys.argv 读取多个文件。每本书都包含了莎士比亚的《哈姆雷特》第二幕中的几句台词。
这是文本文件。将它们保存在与 Python 文件相同的文件夹中:
哈姆雷特 _part1.txt
克劳迪斯国王:乌云怎么还笼罩着你?哈姆雷特
不是这样的,大人;我太晒太阳了。
哈姆雷特 _part2.txt
好哈姆雷特,脱掉你的睡衣,让你的眼睛看起来像一个丹麦的朋友。
不要永远蒙着面纱
在尘土中寻找你高贵的父亲:
你知道这很平常;所有的生命都会死去,穿过自然走向永恒。是的,夫人,这很平常。
使用 sys.argv,我们将告诉 Python 打开每个文件并将其内容打印到控制台。我们还将利用 readline() 方法来读取文本文件的行。
示例 8:使用 sys 模块读取多个文件
import sys
# read files with sys.argv
def read_file(filename):
with open(filename) as file:
while True:
line = file.readline()
if len(line) == 0:
break
print(line)
files = sys.argv[1:]
for filename in files:
read_file(filename)
一旦程序有了 sys.argv 提供的文件名,就会使用 for 循环打开每个文件。在终端中,我们将向 Python 提供文件的名称。
投入
python sys_read_file.py hamlet_part1.txt hamlet_part2.txt
输出
KING CLAUDIUS
How is it that the clouds still hang on you?
HAMLET
Not so, my lord; I am too much i' the sun.
QUEEN GERTRUDE
Good Hamlet, cast thy nighted colour off,
And let thine eye look like a friend on Denmark.
Do not for ever with thy vailed lids
Seek for thy noble father in the dust:
Thou know'st 'tis common; all that lives must die,
Passing through nature to eternity.
HAMLET
Ay, madam, it is common.
额外资源
概括地说,sys 模块为我们提供了对变量和函数的访问,这些变量和函数可用于操纵 Python 运行时环境。
我们可以使用 sys.argv 从命令行或终端向 Python 程序传递参数。在我们的示例中,sys 模块用于将文件名传递给我们的程序,但是您会发现有多种方式可以使用这个工具。
如果你想学习更多的 Python,请点击下面的链接,在那里你可以找到关于 Python 数据类型和捕捉异常的信息。
- 学习如何使用 Python 字典。
- 使用 Python 尝试 catch 来避免常见错误。
如何使用特使
原文:https://www.pythonforbeginners.com/code-snippets-source-code/how-to-use-the-envoy-wrapper
关于特使
最近我偶然发现了特使。Envoy 是子流程模块的包装器,而
应该是 Python 的人性化子流程。
它是由 Kenneth Reitz(“Requests:HTTP for Humans”的作者)写的
为什么使用特使?
它被设计成一个易于使用的替代子流程的方法。
"特使:面向人类的 Python 子流程."
安装特使
特使可从 PyPI 获得,并可与 pip 一起安装。
通过 pip 命令行工具搜索 Envoy 包。
pip search envoy
"特使-运行外部进程的简单 API . "安装特使
$ pip install envoy
进口使节
就像任何其他 Python 模块一样,我们必须首先导入它们。
启动 Python 解释器并输入“import envoy”
import envoy
太好了,特使是进口的,现在我们可以开始发现它的功能等。
特使方法和属性
在 Python 中导入一个模块后,看看该模块提供了哪些函数
、类和方法总是好的。一种方法是使用
“dir(envoy)”。
使用目录(模块)
这将列出在
Envoy 模块中定义的所有函数和变量的名称。
>>> dir(envoy)
这将为您提供如下输出:
['Command', 'ConnectedCommand', 'Response', '__builtins__', '__doc__', '__file__',
'__name__', '__package__', '__path__', '__version__', 'connect', 'core', 'expand_args',
'os', 'run', 'shlex', 'subprocess', 'threading’]
如果希望每行得到一个名字,只需运行一个简单的 for 循环:
>>> for i in dir(envoy): print i
该输出每行显示一个名称:
...
Command
ConnectedCommand
Response
__builtins__
__doc__
__file__
__name__
__package__
__path__
__version__
connect
core
expand_args
os
run
shlex
subprocess
threading
>>>
您还可以使用“help(envoy)”来获取所有功能的文档。
特使用法
让我们来看看特使的“运行”方法。
envoy.run()
要检查我们机器的正常运行时间,我们可以使用“uptime”命令。
r = envoy.run("uptime”)
标准输出
为了查看输出,我们添加了“std_out”:
>>> r.std_out
'15:11 up 6 days, 1:04, 3 users, load averages: 0.55 0.57 0.61
‘
状态代码
要获取状态代码,请将“status_code”添加到对象中。
print r.status_code
0
命令
运行命令,得到响应:
>>> print r
标准误差
要获得标准误差,请添加“std_err”。
r.std_err
历史
获取历史。
r.history
[<response 'uptime'="">]
特使示例
检查镀铬工艺
r = envoy.run("ps aux |grep Chrome")
print r.std_out
在最后一个例子中,我使用了多个命令。
import envoy
cmd = ['date', "uptime", "w"]
r = envoy.run(cmd)
print r.std_out
获取所有命令的状态代码
import envoy
cmd = ['date', "uptime", "w"]
for command in cmd:
r = envoy.run(cmd)
print r.status_code
获取状态代码+每个命令的输出
import envoy
cmd = ['date', "uptime", "w"]
for command in cmd:
r = envoy.run(cmd)
print r.status_code, r.std_out
特使已经成为我处理外部命令调用的主要库。
它被设计成一个易于使用的替代子流程的工具,envoy.run 的便利性真的很好。
更多阅读
https://github.com/kennethreitz/envoy
http://stackoverflow.com/search?q=envoy
如何使用黑客新闻 API
原文:https://www.pythonforbeginners.com/api/how-to-use-the-hacker-news-api
黑客新闻 API–概述
今天我将浏览“黑客新闻的非官方 Python API”,可以在这里找到
什么是黑客新闻?
Hacker News 是一个面向程序员和企业家的社交新闻网站,提供与计算机科学和企业家精神相关的内容。[ 来源
Python 包装器
在如何在 Python 中使用 Reddit API中,我们描述了如何直接访问 Reddit API。另一种方法是使用一个 Reddit 包装器。包装器是一个 API 客户端,通常用于通过调用 API 本身将 API 包装成易于使用的函数。当使用包装器时,您不必关心幕后发生了什么,这对初学者来说有时会更容易。可以把它想象成 python 和 web 服务之间的接口。
入门指南
让我们开始使用 pip 工具安装它。
pip search HackerNews
HackerNews - Python API for Hacker News.
pip install HackerNews
已成功安装 HackerNews 清理… pip 显示 HackerNews —名称:HackerNews 版本:1.3.3 位置:/usr/local/lib/python 2.7/dist-packages 需要:BeautifulSoup4
API 文档
建议您阅读文档,该文档可在这个 Github 页面上获得。该 API 包含几个类(HN 和故事)。这些类为您提供了方法。HN 类可用的方法有:get_top_stories()从 HN 主页返回一个故事对象列表 get_newest_stories()从 HN 最新页面返回一个故事对象列表 Story 类可用的方法有:Print _ Story()–打印一个故事的细节
运行程序
API 的作者在他的 Github 页面上提供了一个例子。该示例打印 Hacker news 的热门文章和新文章。打开您最喜欢的编辑器,复制并粘贴以下代码。
#!/usr/bin/env python
from hn import HN
hn = HN()
# print top 10 stories from homepage
for story in hn.get_top_stories()[:10]:
story.print_story()
print '*' * 50
print ''
# print 10 latest stories
for story in hn.get_newest_stories()[:10]:
story.print_story()
print '*' * 50
print ''
# print all self posts from the homepage
for story in hn.get_top_stories():
if story.is_self_post:
story.print_story()
print '*' * 50
print ''
将其另存为 test_bot.py 并运行。该程序将循环浏览黑客新闻上的每个故事(帖子),并给出 10 个最新的故事。对于每个帖子,它将显示在故事详细信息排名下看到的信息——页面上故事的排名 Story _ id——故事的 id 标题——故事的标题是 _ self _ post——真实的自我/工作故事链接——它指向的 url(无自我帖子)域——链接的域(无自我帖子) 点数–故事提交者的点数/因果关系–提交故事提交者的用户 _ 链接–上面的用户资料链接发布时间–发布时间之前的数量 _ 评论–评论数量 _ 链接–使用 python 包装的 API 到评论页面的链接很好也很简单,但请尝试理解幕后发生的事情。 理解代码中发生了什么是很重要的,一旦你学会了,你就可以使用包装器了。尝试获取关于 Json】和 API 的知识,了解它们大多数是如何工作的。
更多阅读
如何使用 Pexpect 模块
原文:https://www.pythonforbeginners.com/systems-programming/how-to-use-the-pexpect-module-in-python
本文基于来自 http://www.noah.org/wiki/pexpect 和 http://pypi.python.org/pypi/pexpect/的文档
我开始使用 Pexepect 的原因是因为我在寻找一个可以满足我的一些自动化需求的模块(主要是 ssh 和 ftp)。
你可以使用其他模块比如子流程,但是我发现这个模块更容易使用。
注意,这篇文章不是为 Python 初学者写的,但是学习新事物总是很有趣的
什么是 Pexpect?
Pexpect 是一个纯 Python 模块,使 Python 成为控制
和自动化其他程序的更好工具。
Pexpect 基本上是一个模式匹配系统。它运行程序并观察
输出。
当输出与给定的模式匹配时,Pexpect 可以做出响应,就像人类在
输入响应一样。
Pexpect 可以用来做什么?
Pexpect 可以用于自动化、测试和屏幕抓取。
Pexpect 可用于自动化交互式控制台应用程序,如
ssh、ftp、passwd、telnet 等。
它还可以通过“lynx”、“w3m”或其他基于文本的网络浏览器来控制网络应用程序。
安装 Pexpect
Pexpect 的最新版本可以在这里找到
wget http://pexpect.sourceforge.net/pexpect-2.3.tar.gz
tar xzf pexpect-2.3.tar.gz
cd pexpect-2.3
sudo python ./setup.py install
# If your systems support yum or apt-get, you might be able to use the
# commands below to install the pexpect package.
sudo yum install pexpect.noarch
# or
sudo apt-get install python-pexpect
预期方法
Pexpect 中有两个重要的方法:expect()和 send()(或者 sendline()
,它类似于带有换行符的 send()。
expect()方法
等待子应用程序返回给定的强。
您指定的字符串是一个正则表达式,因此您可以匹配复杂的
模式。
记住,任何时候你试图匹配一个需要前瞻的模式,你总是会得到一个最小匹配。
下面将总是返回一个字符:
child.expect('。+')
正确指定您期望返回的文本,您可以添加'.* '到文本的开头
或结尾,以确保捕捉到
个意外字符
这个例子将匹配成功,但将始终不返回任何字符:
child.expect('。*')
一般任何星号*表达式都会尽量少匹配。
给予 expect()的模式也可以是一列正则表达式,
这允许您匹配多个可选响应。
(例如,如果您从服务器获得各种响应)
send()方法
将字符串写入子应用程序。
从孩子的角度来看,这看起来就像有人从终端输入了文本。
之前和之后的属性
在每次调用 expect()之后,before 和 After 属性将被设置为由子应用程序打印的
文本。
before 属性将包含预期字符串模式之前的所有文本。
您可以使用 child.before 来打印连接另一端的输出
之后的字符串将包含与预期模式匹配的文本。
匹配属性被设置为 re MatchObject。
从远程 FTP 服务器连接并下载文件
这将连接到 openbsd ftp 站点并下载递归目录
清单。
您可以在任何应用程序中使用这种技术。
如果您正在编写自动化测试工具,这尤其方便。
同样,这个例子是从复制到这里
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('[[email protected]](/cdn-cgi/l/email-protection)')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')
在第二个例子中,我们可以看到如何从 Pexpect 取回控制权
连接到远程 FTP 服务器并获得控制权
这个例子使用 ftp 登录到 OpenBSD 站点(如上所述),
列出一个目录中的文件,然后将 ftp 会话的交互控制
传递给人类用户。
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('[[email protected]](/cdn-cgi/l/email-protection)')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before # Print the result of the ls command.
child.interact() # Give control of the child to the user.
EOF、超时和行尾
有特殊的模式来匹配文件结束或超时条件。
我不会在这篇文章中写它,而是参考官方的文档
,因为知道它是如何工作的是很好的。
在 Python 中使用平台模块
原文:https://www.pythonforbeginners.com/basics/how-to-use-the-platform-module-in-python
它是用来做什么的?
Python 中的平台模块用于访问底层平台的数据,例如硬件、操作系统和解释器版本信息。
平台模块包括查看平台硬件、操作
系统和程序运行的解释器版本信息的工具。
我如何使用它?
你从在你的程序中导入平台模块开始,就像这样:
导入平台
然后你指定你想要查找的内容(更多内容在下面)。
举个例子,如果你想知道你用的是哪个 python 版本,
只需在平台上添加 python_version(),就像这样:
打印 platform.python_version()
这将返回字符串形式的 Python 版本。
在我的电脑上看起来是这样的:
2.7.3
平台功能
让我们来看看我们可以使用的不同平台功能
platform . architecture() 返回位架构信息
platform.machine() 返回机器类型,如' i386 '。
platform.node() 返回计算机的网络名称(可能不是全限定!)
platform.platform()
返回一个标识底层平台的字符串,其中包含尽可能多的有用信息
。
platform.processor() 返回(真实的)处理器名,如' amdk6 '。
platform . python _ build()
返回一个元组(buildno,builddate ),以字符串形式表示 Python 编译号和
日期。
platform . python _ compiler()
返回一个字符串,标识用于编译 Python 的编译器。
platform . python _ version()
以字符串' major.minor.patchlevel '的形式返回 Python 版本
platform . python _ implementation()
返回标识 Python 实现的字符串。
可能的返回值有:' CPython ',' IronPython ',' Jython ',' PyPy '。
platform.release()
返回系统的版本,如“2.2.0”或“NT”
platform.system()
返回系统/操作系统名称,例如“Linux”、“Windows”或“Java”。
platform.version()
返回系统的发布版本,例如“德加的#3”
platform.uname()
返回一个字符串元组(系统、节点、版本、版本、机器、处理器)
标识底层平台。
操作系统和硬件信息
让我们展示一些带有输出的例子,看看这是如何工作的。
(你可以在这里找到更多例子)
import platform
print 'uname:', platform.uname()
print
print 'system :', platform.system()
print 'node :', platform.node()
print 'release :', platform.release()
print 'version :', platform.version()
print 'machine :', platform.machine()
print 'processor:', platform.processor()
输出
uname: ('Linux ',' Mwork ',' 3.5.0-21-generic ',' 32-Ubuntu SMP Tue Dec 11 18:51:59
UTC 2012 ',' x86_64 ',' x86_64 ')
系统:Linux
节点:Mwork
版本:3 . 5 . 0-21-通用
版本:# 32-Ubuntu SMP Tue 11 Dec 11 18:51:59 UTC 2012
机器:x86_64
处理器:x86_64
来源
请查看以下网址了解更多信息
http://docs.python.org/2/library/platform.html
http://www.doughellmann.com/PyMOTW/platform/
如何使用 Python 图像库
原文:https://www.pythonforbeginners.com/gui/how-to-use-the-python-imaging-library
PIL 已被弃用,过时了。请用枕头。
了解如何使用枕头
如何使用 Python 中的随机模块
原文:https://www.pythonforbeginners.com/random/how-to-use-the-random-module-in-python
在这篇文章中,我将描述 Python 中随机模块的使用。随机模块提供对支持许多操作的功能的访问。也许最重要的是它允许你生成随机数。
Python 中什么时候使用 Random 模块?
如果你想让计算机在一个给定的范围内挑选一个随机数,从一个 python 列表中挑选一个随机元素,从一副牌中挑选一张随机牌,掷硬币等等,你可以使用 python 中的 random 模块。您还可以使用随机模块来创建随机字符串,同时选择密码以使您的密码数据库更加安全,或者为您网站的随机页面功能提供动力。
Python 中的随机函数
随机模块包含一些非常有用的函数,即 randint()函数、Random()函数、choice()函数、randrange()函数和 shuffle()函数。让我们逐一讨论这些功能。
Python 中的 randint()函数
python random 模块中定义的 randint()函数可用于在一个范围内创建随机字符串。该函数将两个数字作为其输入参数。第一个输入参数是范围的开始,第二个输入参数是范围的结束。执行后,randint()函数返回给定范围内的随机整数。
如果我们想要一个随机整数,我们可以使用 randint()函数。例如,您可以生成 1 到 5 之间的随机整数,如下例所示。
import random
print random.randint(0, 5)
上述代码将输出 1、2、3、4 或 5。这里,您应该确保 randint()函数中的第一个输入参数应该小于第二个输入参数。否则,程序会出错。
random()函数
python random 模块中的 random()函数用于生成 0 到 1 之间的随机数。执行时,random()函数返回一个介于 0 和 1 之间的浮点数。
如果你想要一个更大的数字,你可以把它乘以一个更大的值。例如,要创建一个 0 到 100 之间的随机数,可以将 random()函数的输出乘以 100,如下所示。
import random
random.random() * 100
choice()函数
choice()函数用于从一个集合对象中选择一个随机元素,比如列表、集合、元组等。该函数将集合对象作为其输入参数,并返回一个随机元素。
例如,通过将颜色名称列表作为输入传递给 choice()函数,可以从颜色列表中选择一种随机颜色,如下例所示。
random.choice( ['red', 'black', 'green'] ).
choice 函数通常用于从列表中选择一个随机元素。
import random
myList = [2, 109, False, 10, "Lorem", 482, "Ipsum"]
random.choice(myList)
函数的作用是
顾名思义,shuffle 函数将列表中的元素打乱顺序。shuffle()函数将一个列表作为输入参数。执行后,列表中的元素以随机的顺序被打乱,如下例所示。
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
Output:
# print x gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary
randrange()函数
python random 模块中的 randrange()函数用于从给定的范围中选择一个随机元素。它采用三个数字作为输入参数,即开始、停止和步进。执行后,它从范围(开始、停止、步进)中生成一个随机选择的元素。要了解 range()函数的工作原理,可以阅读这篇关于 python range 的文章。
random.randrange(start, stop[, step])
import random
for i in range(3):
print random.randrange(0, 101, 5)
实际上,randrange()函数是 choice()函数和 range()函数的组合。
Python 中随机模块的代码示例
下面的代码示例使用 choice()函数来计算 10000 次投掷中正面和反面的数量。为此,我们定义了一个名为 outcomes 的字典来存储正面和反面的数量。接下来,我们使用 python 字典的 keys()方法来获取列表["heads "," tails"]。之后,我们使用 choice()函数从列表中随机选择一个值,并根据输出更新结果字典。
import random
import itertools
outcomes = { 'heads':0,
'tails':0,
}
sides = outcomes.keys()
for i in range(10000):
outcomes[ random.choice(sides) ] += 1
print 'Heads:', outcomes['heads']
print 'Tails:', outcomes['tails']
只允许两种结果,所以与其使用数字并转换它们,不如将单词“正面”和“反面”与 choice()一起使用。
使用结果名称作为关键字,将结果列表显示在字典中。
$ python random_choice.py
Heads: 4984
Tails: 5016
结论
在本文中,我们讨论了 Python 中 random 模块的不同函数。我们还讨论了一个使用 choice()函数模拟抛硬币的代码示例。
要了解更多关于 python 编程的知识,你可以阅读这篇关于 Python 中的列表理解的文章。你可能也会喜欢这篇关于字符串操作的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
如何在 Python 中使用 Vimeo API
原文:https://www.pythonforbeginners.com/api/how-to-use-the-vimeo-api-in-python
概观
In this post we will be looking on how to use the Vimeo API in Python.
关于 Vimeo API
Vimeo offers an API which lets us integrate with their site and build applications
on top of their data.
Vimeo provides a "[Simple API](https://developer.vimeo.com/apis/simple "simple_api")" and an "[Advanced API](https://developer.vimeo.com/apis/advanced "advanced_api")".
To perform authenticated read/write requests on videos, users, groups, channels,
albums, or upload, you will have to use the Advanced API.
It uses OAuth for authentication, so you will first need to sign up.
When using the Simple API, you don’t need to register or authenticate your app.
One of the drawback with using the Simple API is that it’s limited to public data
and is read-only.
The response limits in the Simple API include up to 20 items per page.
Vimeos API provides different Response formats, and they all return the exact
same data.
入门指南
After looking at the website of Vimeo, I found out that I can start out with this
URL: http://vimeo.com/api/v2/video/video_id.output
the video_id is the ID of the video you want information for.
the output specifies which type that we want (json, xml)
常见 Vimeo 请求
Making a User Request
Making a Video Request
Making an Activity Request
Making a Group Request
Making a Channel Request
Making an Album Request
使用 Vimeo API 获取数据
This script will show how you can set up the script to make a Video request from
Vimeo.
import requests
import json
r = requests.get("http://vimeo.com/api/v2/video/48082757.json")
r.text
data = json.loads(r.text)
'do something with the data'
Vimeo has been kind enough to provide some API examples for us which can be found
on their GitHub repository. [https://github.com/vimeo/vimeo-api-examples](https://github.com/vimeo/vimeo-api-examples "github_api_vimeo")
更多阅读
[http://developer.vimeo.com/apis/](https://developer.vimeo.com/apis/ "vimeo_api")
如何在 Python 中使用 urllib2
原文:https://www.pythonforbeginners.com/python-on-the-web/how-to-use-urllib2-in-python
概观
虽然这篇文章的标题是“Urllib2”,但我们将展示一些使用 Urllib 的例子,因为它们经常一起使用。
这将是 urllib2 的一篇介绍文章,在这里我们将
关注获取 URL、请求、文章、用户代理和错误处理。
有关更多信息,请参见官方文档。
此外,本文是为 Python 版本编写的
HTTP 基于请求和响应——客户端发出请求,而
服务器发送响应。
互联网上的程序可以作为客户端(访问资源)或服务器(提供服务)。
URL 标识互联网上的资源。
什么是 Urllib2?
urllib2 是一个 Python 模块,可以用来获取 URL。
它定义了函数和类来帮助 URL 操作(基本和摘要
认证、重定向、cookies 等)
神奇之处始于导入 urllib2 模块。
urllib 和 urllib2 有什么区别?
虽然两个模块都做与 URL 请求相关的事情,但是它们有不同的
功能
urllib2 可以接受一个请求对象来设置 URL 请求的头,
urllib 只接受一个 URL。
urllib 提供了 urlencode 方法,用于生成
GET 查询字符串, urllib2 没有这个功能。
正因为如此,urllib 和 urllib2 经常一起使用。
有关更多信息,请参见文档。
Urllib
Urllib 2
什么是 urlopen?
urllib2 以 urlopen 函数的形式提供了一个非常简单的接口。
这个函数能够使用各种不同的协议
(HTTP、FTP、…)获取 URL
只需将 URL 传递给 urlopen() 就可以获得一个针对远程数据的“类文件”句柄。
另外, urllib2 提供了一个接口来处理常见的情况—
,比如基本认证、cookies、代理等等。
这些是由称为处理程序和打开程序的对象提供的。
获取 URL
这是图书馆最基本的使用方法。
下面你可以看到如何用 urllib2 做一个简单的请求。
首先导入 urllib2 模块。
将响应放入变量(response)
响应现在是一个类似文件的对象。
将响应中的数据读入一个字符串(html)
用那根绳子做点什么。
注意如果 URL 中有空格,您将需要使用 urlencode 解析它。
让我们来看一个例子。
import urllib2
response = urllib2.urlopen('https://www.pythonforbeginners.com/')
print response.info()
html = response.read()
# do something
response.close() # best practice to close the file
Note: you can also use an URL starting with "ftp:", "file:", etc.).
远程服务器接受传入的值,并格式化一个纯文本响应
发回。
来自 urlopen() 的返回值通过 info() 方法访问来自 HTTP 服务器
的头,并通过
read() 和 readlines() 等方法访问远程资源的数据。
此外,由 urlopen() 返回的文件对象是可迭代的。
简单的 urllib2 脚本
让我们展示另一个简单的 urllib2 脚本示例
import urllib2
response = urllib2.urlopen('http://python.org/')
print "Response:", response
# Get the URL. This gets the real URL.
print "The URL is: ", response.geturl()
# Getting the code
print "This gets the code: ", response.code
# Get the Headers.
# This returns a dictionary-like object that describes the page fetched,
# particularly the headers sent by the server
print "The Headers are: ", response.info()
# Get the date part of the header
print "The Date is: ", response.info()['date']
# Get the server part of the header
print "The Server is: ", response.info()['server']
# Get all data
html = response.read()
print "Get all data: ", html
# Get only the length
print "Get the length :", len(html)
# Showing that the file object is iterable
for line in response:
print line.rstrip()
# Note that the rstrip strips the trailing newlines and carriage returns before
# printing the output.
使用 Urllib2 下载文件
这个小脚本将从 pythonforbeginners.com 网站下载一个文件
import urllib2
# file to be written to
file = "downloaded_file.html"
url = "https://www.pythonforbeginners.com/"
response = urllib2.urlopen(url)
#open the [file for writing](https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python)
fh = open(file, "w")
# read from request while writing to file
fh.write(response.read())
fh.close()
# You can also use the with statement:
with open(file, 'w') as f: f.write(response.read())
这个脚本的不同之处在于我们使用了‘WB’,这意味着我们打开了
文件二进制文件。
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
output = open('test.mp3','wb')
output.write(mp3file.read())
output.close()
Urllib2 请求
Request 对象代表您正在发出的 HTTP 请求。
最简单的形式是创建一个请求对象,它指定了您希望
获取的 URL。
用这个请求对象调用 urlopen 将返回所请求的 URL
的响应对象。
urllib2 类下的请求函数接受 url 和参数。
当您不包含数据(只传递 url)时,发出的请求
实际上是一个 GET 请求
当您包含数据时,发出的请求是 POST 请求,其中
url 将是您的 post url,参数将是 http post content。
让我们看看下面的例子
import urllib2
import urllib
# Specify the url
url = 'https://www.pythonforbeginners.com'
# This packages the request (it doesn't make it)
request = urllib2.Request(url)
# Sends the request and catches the response
response = urllib2.urlopen(request)
# Extracts the response
html = response.read()
# Print it out
print html
您可以在请求上设置传出数据,以将其发送到服务器。
此外,您可以将关于数据的数据额外信息(“元数据”)或
about 请求本身传递给服务器——这些信息作为 HTTP
“headers”发送。
如果您想要发布数据,您必须首先将数据创建到字典中。
确保您理解代码的作用。
# Prepare the data
query_args = { 'q':'query string', 'foo':'bar' }
# This urlencodes your data (that's why we need to import urllib at the top)
data = urllib.urlencode(query_args)
# Send HTTP POST request
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
html = response.read()
# Print the result
print html
用户代理
浏览器通过用户代理头标识自己。
默认情况下,urllib2 将自己标识为 Python-urllib/x.y
,其中 x 和 y 是 Python 版本的主版本号和次版本号。
这可能会混淆网站,或者干脆不工作。
使用 urllib2,您可以使用 urllib2 添加自己的标题。
你想这么做的原因是一些网站不喜欢被程序浏览。
如果你正在创建一个访问其他人的网络资源的应用程序,
在你的请求中包含真实的用户代理信息是礼貌的,
这样他们可以更容易地识别点击的来源。
当您创建请求对象时,您可以将您的头添加到字典
中,并在打开请求之前使用 add_header()设置用户代理值。
看起来大概是这样的:
# Importing the module
import urllib2
# Define the url
url = 'http://www.google.com/#q=my_search'
# Add your headers
headers = {'User-Agent' : 'Mozilla 5.10'}
# Create the Request.
request = urllib2.Request(url, None, headers)
# Getting the response
response = urllib2.urlopen(request)
# Print the headers
print response.headers
也可以用“add_header()”添加头
语法:Request.add_header(key,val)
下面的例子,使用 Mozilla 5.10 作为用户代理,这也是
将在 web 服务器日志文件中显示的内容。
import urllib2
req = urllib2.Request('http://192.168.1.2/')
req.add_header('User-agent', 'Mozilla 5.10')
res = urllib2.urlopen(req)
html = res.read()
print html
这是将在日志文件中显示的内容。
“GET/HTTP/1.1?200 151”——“Mozilla 5.10?
urllib.urlparse
urlparse 模块提供了分析 URL 字符串的函数。
它定义了一个标准接口,将统一资源定位符(URL)
字符串分成几个可选部分,称为组件,称为
(方案、位置、路径、查询和片段)
假设你有一个网址:【http://www.python.org:80/index.html
方案应该是 http
地点将会是 www.python.org:80
路径是 index.html
我们没有任何查询和片段
最常见的函数是 urljoin 和 urlsplit
import urlparse
url = "http://python.org"
domain = urlparse.urlsplit(url)[1].split(':')[0]
print "The domain name of the url is: ", domain
有关 urlparse 的更多信息,请参见官方文档。
urllib,urlencode
当您通过 URL 传递信息时,您需要确保它只使用特定的允许字符。
允许的字符是任何字母字符、数字和一些在 URL 字符串中有意义的特殊
字符。
最常见的编码字符是空格字符。
每当您在 URL 中看到加号(+)时,就会看到此字符。
这代表空格字符。
加号充当代表 URL 中空格的特殊字符
可以通过对参数进行编码并将它们附加到 URL 上来将参数传递给服务器。
让我们看看下面的例子。
import urllib
import urllib2
query_args = { 'q':'query string', 'foo':'bar' } # you have to pass in a dictionary
encoded_args = urllib.urlencode(query_args)
print 'Encoded:', encoded_args
url = 'http://python.org/?' + encoded_args
print urllib2.urlopen(url).read()
如果我现在打印它,我会得到这样一个编码字符串:
q = query+string&foo = bar
Python 的 urlencode 接受变量/值对,并创建一个正确转义的
querystring:
from urllib import urlencode
artist = "Kruder & Dorfmeister"
artist = urlencode({'ArtistSearch':artist})
这将变量 artist 设置为等于:
输出:ArtistSearch = Kruder+% 26+dorf meister
错误处理
这一段错误处理是基于 Voidspace.org.uk 大文章中的信息:
urllib 2——缺失的手册
当 urlopen 无法处理响应时,它会引发 URLError 。
HTTPError 是在 HTTP URLs 的具体情况下引发的 URLError 的子类。
URLError
通常,引发 URLError 的原因是没有网络连接,
或者指定的服务器不存在。
在这种情况下,引发的异常将有一个“原因”属性,
,它是一个包含错误代码和文本错误消息的元组。
URLError 示例
req = urllib2.Request('http://www.pretend_server.org')
try:
urllib2.urlopen(req)
except URLError, e:
print e.reason
(4, 'getaddrinfo failed')
HTTPError
来自服务器的每个 HTTP 响应都包含一个数字“状态代码”。
有时,状态代码表示服务器无法满足请求。
默认处理程序将为您处理其中的一些响应(例如,
如果响应是一个“重定向”,请求客户端从不同的 URL 获取文档
, URL lib 2 将为您处理它)。
对于那些它不能处理的,urlopen 会抛出一个 HTTPError。
典型的错误包括“404”(找不到页面)、“403”(禁止请求)、
和“401”(需要验证)。
当出现错误时,服务器通过返回 HTTP 错误代码
和错误页面进行响应。
您可以在返回的页面上使用 HTTPError 实例作为响应。
这意味着除了 code 属性之外,它还有 read、geturl、
和 info 等方法。
req = urllib2.Request('http://www.python.org/fish.html')
try:
urllib2.urlopen(req)
except URLError, e:
print e.code
print e.read()
from urllib2 import Request, urlopen, URLError
req = Request(someurl)
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server could not fulfill the request.'
print 'Error code: ', e.code
else:
# everything is fine
请看看下面的链接,以获得对 Urllib2
库的更多了解。
资料来源和进一步阅读
http://pymotw . com/2/urllib 2/
【http://www . kensjauson . com/【http://www . voidspace . org . uk/python/articles/urllib 2 . shtml】
如何用 Python 写注释
原文:https://www.pythonforbeginners.com/strings/how-to-write-comments-in-python
python 中的注释是源代码的一部分,不被 python 解释器执行。注释对应用程序没有贡献任何功能,对应用程序的用户没有任何意义。但是注释对程序员有很大的帮助。注释增加了源代码的可读性和可理解性,并帮助程序员重构或调试代码,同时为应用程序中的新功能添加源代码。在本文中,我们将看到如何使用不同的方式在 python 中编写注释。
如何用 Python 写单行注释?
我们可以用# symbol 写一行 python 注释。在 python 中,任何写在# till 换行符之后的东西,包括符号本身,都被认为是注释。每当遇到换行符时,单行注释就会终止。我们可以在程序的任何地方使用#符号开始一行注释,在符号变成注释后使用整个语句。
下面是一个示例代码,其中一行注释写在一个 python 字典中。
myDict={"name":"PythonForBeginners.com",
#This is a single line comment inside a python dictionary
"acronym":"PFB"
}
print(myDict["acronym"])
我们也可以在 python 语句后开始单行注释。
myDict={"name":"PythonForBeginners.com",
#This is a single line comment inside a python dictionary
"acronym":"PFB"
}
print(myDict["acronym"]) #This is single line comment which starts after a python statement
如何用 Python 写多行注释?
理论上,python 没有多行注释的语法,但是我们可以使用其他方式,比如多行字符串和单行注释来编写 python 中的多行注释。
我们可以使用单行注释在 python 中编写多行注释,方法是在连续的行上编写单行注释,如下例所示。
#This is multiline comment
#written using single line comments
#for a demonstration
myDict={"name":"PythonForBeginners.com",
"acronym":"PFB"
}
print(myDict["acronym"])
我们也可以在 python 语句后开始多行注释,同时用#符号实现多行注释,因为它必然表现为单行注释。
#This is multiline comment
#written using single line comments
#for a demonstration
myDict={"name":"PythonForBeginners.com",
"acronym":"PFB"
}
print(myDict["acronym"]) #This is multiline comment after a python statement
#written using single line comments
#for a demonstration
为了用 python 写多行注释,我们也可以使用多行字符串。如果我们没有给任何变量分配一个多行字符串,解释器将分析和评估该多行字符串,但是不会为该多行字符串生成字节码,因为没有地址可以分配给它们。实际上,多行字符串将作为多行注释工作。以下是使用多行字符串编写的多行注释的示例。
"""This is multiline comment
written using multi line strings
for a demonstration"""
myDict={"name":"PythonForBeginners.com",
"acronym":"PFB"
}
print(myDict["acronym"])
我们必须记住,使用多行字符串编写的多行注释不是真正的注释,它们只是未赋值的字符串常量。因此,它们应该遵循适当的缩进,并且只能从新行开始。如果我们试图在任何 python 语句后使用多行字符串编写多行注释,将会导致语法错误。
myDict={"name":"PythonForBeginners.com",
"acronym":"PFB"
}
print(myDict["acronym"])"""This is not a multiline comment and
will cause syntax error in the program"""
结论
在本文中,我们看到了如何使用#符号和多行字符串在 python 中编写注释。更多文章敬请关注。
如何使用 MySQL 连接器/Python
原文:https://www.pythonforbeginners.com/code-snippets-source-code/how-use-mysql-connectorpython
MySQL Connector/Python 是 Oracle 自己发布的一个驱动程序,让用 Python 连接 MySQL 数据库变得更容易。MySQL connector/Python 支持 Python 2.0 及更高版本的所有版本,也包括 3.3 及更高版本。
要安装 MySQL Connector/Python,只需使用 pip 安装软件包。
pip install mysql-connect-python --allow-external mysql-connector-python
连接到数据库并提交给它非常简单。
import mysql.connector
connection = mysql.connector.connect(user="username",
password="password",
host="127.0.0.1",
database="database_name")
cur = connection.cursor()
cur.execute("INSERT INTO people (name, age) VALUES ('Bob', 25);")
connection.commit()
cur.close()
connection.close()
Python 命令行 IMDB Scraper
原文:https://www.pythonforbeginners.com/code-snippets-source-code/imdb-crawler
概观
这个脚本将要求输入电影名称和年份,然后向 IMDB 查询。
命令行 IMDB 刮刀
第一步是导入必要的模块。
#!/usr/bin/env python27
#Importing the modules
from BeautifulSoup import BeautifulSoup
import sys
import urllib2
import re
import json
#Ask for movie title
title = raw_input("Please enter a movie title: ")
#Ask for which year
year = raw_input("which year? ")
#Search for spaces in the title string
raw_string = re.compile(r' ')
#Replace spaces with a plus sign
searchstring = raw_string.sub('+', title)
#Prints the search string
print searchstring
#The actual query
url = "http://www.imdbapi.com/?t=" + searchstring + "&y="+year
request = urllib2.Request(url)
response = json.load(urllib2.urlopen(request))
print json.dumps(response,indent=2)
好好享受吧!
用 Python 实现 Deque
原文:https://www.pythonforbeginners.com/deque/implement-deque-in-python
双端队列是线性数据结构,我们可以用它来执行后进先出(LIFO)操作和先进先出(FIFO)操作。Deques 在现实生活中有很多应用,比如在软件中实现撤销操作,在 web 浏览器中存储浏览历史。在本文中,我们将使用链表在 python 中实现 deque。
如何在 python 中使用链表实现 deque?
链表是由包含数据的节点组成的线性数据结构。链表中的每个节点都指向链表中的另一个节点。为了使用链表在 python 中实现 deque,我们必须在链表的两端执行插入和删除操作。此外,我们还必须记录队列的长度。
为了创建一个链表,我们将定义一个节点,它将有一个数据字段和下一个字段。数据字段包含实际数据,下一个字段引用链表中的下一个节点。python 中的节点类可以定义如下。
class Node:
def __init__(self,data):
self.data=data
self.next=None
为了使用链表实现 dequeue,我们将定义一个类 dequeue,它包含一个对链表第一个元素的名为 front 的引用和一个 dequeSize 字段来保持 dequeue 的大小,如下所示。
class Deque:
def __init__(self):
self.front=None
self.dequeSize=0
在 python 中的 deque 中插入元素
我们可以在队列的前后插入。为了在前面的队列中插入一个元素,我们将在链表的开头添加这个元素。由于链表的开始被 front 引用,我们将在当前被 front 引用的节点之前添加元素,然后将 dequeSize 增加 1。这可以如下实现。
def insertAtFront(self,data):
temp=Node(data)
if self.front==None:
self.front=temp
self.dequeSize=self.dequeSize+1
else:
temp.next=self.front
self.front=temp
self.dequeSize=self.dequeSize+1
要在队列的后面插入一个元素,我们必须将该元素添加到链表的末尾。之后,我们将如下增加 dequeSize。
def insertAtRear(self,data):
temp=Node(data)
if self.front==None:
self.front=temp
self.dequeSize=self.dequeSize+1
else:
curr=self.front
while curr.next!=None:
curr=curr.next
curr.next=temp
self.dequeSize=self.dequeSize+1
在 python 中从队列中删除元素
我们可以从队列的前面和后面删除一个元素。在删除元素之前,我们将检查队列是否为空。如果 dequee 为空,即 front 指向 None,我们将使用 python try except 引发一个异常,并显示一条消息,说明 dequee 为空。
要从队列的前面删除一个元素,我们必须从前面引用的链表的开头删除这个元素。删除前面的元素后,我们将把 dequeSize 减 1。这可以如下实现。
def delFromFront(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
temp=self.front
self.front=self.front.next
self.dequeSize=self.dequeSize-1
del temp
except Exception as e:
print(str(e))
为了删除队列后面的元素,我们将删除链表的最后一个元素。删除最后一个元素后,我们将把 dequeSize 减 1。这可以如下实现。
def deleteFromRear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
curr=self.front
prev=None
while curr.next!=None:
prev=curr
curr=curr.next
prev.next=curr.next
self.dequeSize=self.dequeSize-1
del curr
except Exception as e:
print(str(e))
检查队列的大小
要检查队列的大小,我们只需检查队列的 dequeSize 字段中的值。这可以如下进行。
def dequeLength(self):
return self.dequeSize
检查队列是否为空
要检查 deque 是否为空,我们必须检查 dequeSize 是否为零。我们可以实现 isEmpty()方法,如果 dequeSize 为零,该方法返回 True,否则返回 False,如下所示。
def isEmpty(self):
if self.dequeSize==0:
return True
return False
检查队列中的前后元素
为了检查队列的前端元素,我们将定义一个 getfront()方法,该方法返回链表的第一个元素,如下所示。
def getfront(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
return self.front.data
except Exception as e:
print(str(e))
为了检查队列的尾部元素,我们将定义一个方法 getrear(),该方法返回链表的最后一个元素,如下所示。
def getrear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
curr=self.front
while curr.next!=None:
curr=curr.next
return curr.data
except Exception as e:
print(str(e))
python 中完整的工作代码实现 deque 如下。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 5 23:41:28 2021
@author: aditya1117
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class Deque:
def __init__(self):
self.front=None
self.dequeSize=0
def isEmpty(self):
if self.dequeSize==0:
return True
return False
def dequeLength(self):
return self.dequeSize
def insertAtFront(self,data):
temp=Node(data)
if self.front==None:
self.front=temp
self.dequeSize=self.dequeSize+1
else:
temp.next=self.front
self.front=temp
self.dequeSize=self.dequeSize+1
def insertAtRear(self,data):
temp=Node(data)
if self.front==None:
self.front=temp
self.dequeSize=self.dequeSize+1
else:
curr=self.front
while curr.next!=None:
curr=curr.next
curr.next=temp
self.dequeSize=self.dequeSize+1
def delFromFront(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
temp=self.front
self.front=self.front.next
self.dequeSize=self.dequeSize-1
del temp
except Exception as e:
print(str(e))
def deleteFromRear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
curr=self.front
prev=None
while curr.next!=None:
prev=curr
curr=curr.next
prev.next=curr.next
self.dequeSize=self.dequeSize-1
del curr
except Exception as e:
print(str(e))
def getfront(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
return self.front.data
except Exception as e:
print(str(e))
def getrear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
curr=self.front
while curr.next!=None:
curr=curr.next
return curr.data
except Exception as e:
print(str(e))
结论
在本文中,我们研究了 deque 背后的概念,并使用 python 中的链表实现了它。为了更深入地了解它,并理解 dequee 与内置数据结构(如 python dictionary 、list 和 set)有何不同,请复制上面给出的完整代码,将其粘贴到您的 IDE 中,并试验 dequee 操作。请继续关注更多内容丰富的文章。
用 Python 实现队列
原文:https://www.pythonforbeginners.com/queue/implement-queue-in-python
队列是一种数据结构,它遵循先进先出(FIFO)的顺序来访问元素。在一个队列中,我们只能访问首先被添加的当前元素。队列在诸如广度优先搜索、计算机资源共享和进程管理等应用中有许多用途。在本文中,我们将尝试用 python 实现带链表的队列数据结构。
使用链表在 Python 中实现队列
链表是一种线性数据结构,其中每个数据对象指向另一个对象。要用链表实现一个队列,我们必须从链表中插入和删除元素,这样首先添加的元素只能被访问。只有当我们在链表的末尾插入元素,并从链表的开头访问或删除元素时,这才是可能的。这样,最老的元素将位于链表的开始,并且可以被访问或删除。
为了在 python 中实现一个带链表的队列,我们将首先定义一个节点对象,该对象将包含当前元素,并指向紧接在它之后插入的节点。在 python 中,该节点可以按如下方式实现。
class Node:
def __init__(self,data):
self.data=data
self.next=None
当我们用链表实现一个队列时,它将有一个名为 front 的元素,它将引用链表中插入的最老的元素,即第一个元素。所有其他元素都可以通过它来访问。它还将包含一个名为 queueSize 的变量,该变量将包含队列的长度。我们可以用 python 实现一个空队列,如下所示。
class Queue:
def __init__(self):
self.front=None
self.queueSize=0
用 Python 实现队列中的入队操作
当我们在队列中插入一个元素时,这个操作叫做入队操作。为了在链表的帮助下实现队列中的入队操作,对于每次插入,我们将在链表的末尾添加要插入的元素。这样,最近的元素总是在链表的末尾,最老的元素总是在链表的前面。将元素插入队列后,我们还将获得队列的大小,并将大小增加 1。可以使用 python 中的链表实现入队操作,如下所示。
def enQueue(self,data):
temp=Node(data)
if self.front is None:
self.front=temp
self.queueSize= self.queueSize+1
else:
curr=self.front
while curr.next!=None:
curr=curr.next
curr.next=temp
self.queueSize=self.queueSize+1
用 python 实现队列中的出列操作
当我们从队列中取出一个元素时,这个操作被称为出列操作。要从队列中取出的元素是队列中最老的元素。如我们所知,在入队操作期间,我们将最近的元素添加到链表的末尾,而最老的元素位于链表的开始,由队列的前端指向,因此我们将移除前端指向的元素,并将前端指向下一个最老的元素。在执行出列操作之前,我们将检查队列是否为空。如果队列为空,即 front 指向 None,我们将使用 python try except 引发一个异常,并显示一条消息:队列为空。我们可以如下实现出列操作。
def deQueue(self):
try:
if self.front == None:
raise Exception("Queue is Empty")
else:
temp=self.front
self.front=self.front.next
tempdata=temp.data
self.queueSize= self.queueSize-1
del temp
return tempdata
except Exception as e:
print(str(e))
如何访问队列的前端元素
由于队列的前端元素被前端引用,我们只需返回前端指向的节点中的数据。它可以按如下方式实现。
def front_element(self):
try:
if self.front == None:
raise Exception("Queue is Empty")
else:
return self.front.data
except Exception as e:
print(str(e))
获取队列的大小
因为我们将队列的当前大小保存在 queueSize 中,所以我们只需返回队列的 queueSize 元素中的值。这可以如下进行。
def size(self):
return self.queueSize
检查队列是否为空
前面的元素是指队列中最老的元素。如果队列中没有元素,前端将指向 None。因此,要检查队列是否为空,我们只需检查前端是否指向 None。我们可以实现 isEmpty()方法来检查队列是否为空,如下所示。
def isEmpty(self):
if self.queueSize==0:
return True
else:
return False
使用 python 中的链表实现队列的完整工作代码如下。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 00:13:19 2021
@author: aditya1117
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class Queue:
def __init__(self):
self.front=None
self.queueSize=0
def enQueue(self,data):
temp=Node(data)
if self.front is None:
self.front=temp
self.queueSize= self.queueSize+1
else:
curr=self.front
while curr.next!=None:
curr=curr.next
curr.next=temp
self.queueSize=self.queueSize+1
def deQueue(self):
try:
if self.front == None:
raise Exception("Queue is Empty")
else:
temp=self.front
self.front=self.front.next
tempdata=temp.data
self.queueSize= self.queueSize-1
del temp
return tempdata
except Exception as e:
print(str(e))
def isEmpty(self):
if self.queueSize==0:
return True
else:
return False
def size(self):
return self.queueSize
def front_element(self):
try:
if self.front == None:
raise Exception("Queue is Empty")
else:
return self.front.data
except Exception as e:
print(str(e))
结论
在本文中,我们使用 python 中的链表实现了队列及其所有操作。为了更深入地了解它,并理解 queue 与内置的数据结构(如 python dictionary 、list 和 set)有何不同,复制上面示例中给出的完整代码,将其粘贴到您的 IDE 中,并试验其中的操作。请继续关注更多内容丰富的文章。
在 Python 中实现堆栈
原文:https://www.pythonforbeginners.com/data-types/implement-stack-in-python
栈是一种数据结构,它遵循后进先出(LIFO)的顺序来访问元素。在堆栈中,我们只能访问最近添加的元素。堆栈在表达式处理、回溯和函数调用等应用中有很多用途。在本文中,我们将尝试用 python 实现带链表的堆栈数据结构。
使用链表在 Python 中实现堆栈
链表是一种线性数据结构,其中每个数据对象指向另一个对象。为了用链表实现一个堆栈,我们将不得不执行插入和删除,以及从链表中删除元素,这样它将花费恒定的时间。只有当我们在链表的开头插入和删除元素时,这才是可能的。
为了在 python 中实现带链表的堆栈,我们将首先定义一个 node 对象,它将包含当前元素,并使用引用 next 指向插入它之前的节点。在 python 中,该节点可以按如下方式实现。
class Node:
def __init__(self,data,size):
self.data=data
self.next=None
当我们用链表实现一个堆栈时,它将有一个名为 top 的元素,这个元素将引用链表中最近插入的元素。所有其他元素都可以通过它来访问。我们可以用 python 实现一个空栈,top 初始化为 None,stackSize 初始化为 0,如下所示。
class Stack:
def __init__(self):
self.top=None
self.stackSize=0
在 Python 中实现栈中的推送操作
当我们将一个元素插入到堆栈中时,这个操作叫做 push 操作。为了在链表的帮助下实现栈中的 push 操作,对于每一次插入,我们将在链表的开头添加要插入的元素。这样,最近的元素将总是在链表的开始。然后,我们将堆栈的顶部元素指向链表的开头,并将 stackSize 递增 1。可以使用 python 中的链表实现推送操作,如下所示。
def push(self,data):
temp=Node(data)
if self.top is None:
self.top=temp
self.stackSize= self.stackSize+1
else:
temp.next=self.top
self.top=temp
self.stackSize=self.stackSize+1
用 Python 实现堆栈中的弹出操作
当我们从堆栈中取出一个元素时,这个操作被称为弹出操作。要从堆栈中取出的元素是最近添加到堆栈中的元素。正如我们所知,在推送操作中,我们将最近的元素添加到堆栈顶部指向的链表的开头,因此我们将删除顶部指向的元素,并将顶部指向下一个最近的元素。在执行弹出操作之前,我们将检查堆栈是否为空。如果堆栈为空,即 top 指向 None,我们将使用 python try except 引发一个异常,并显示堆栈为空的消息。我们可以如下实现 pop 操作。
def pop(self):
try:
if self.top == None:
raise Exception("Stack is Empty")
else:
temp=self.top
self.top=self.top.next
tempdata=temp.data
self.stackSize= self.stackSize-1
del temp
return tempdata
except Exception as e:
print(str(e))
如何访问栈顶元素
由于栈顶的元素被 top 引用,我们只需返回 top 指向的节点中的数据。它可以按如下方式实现。
def top_element(self):
try:
if self.top == None:
raise Exception("Stack is Empty")
else:
return self.top.data
except Exception as e:
print(str(e))
获取堆栈的大小
因为我们在 stackSize 变量中保留了当前的堆栈大小,所以我们只需返回 stackSize 变量 top 中的值。这可以如下进行。
def size(self):
return self.stackSize
检查堆栈是否为空
元素 top 指的是堆栈中最近的元素。如果堆栈中没有元素,top 将指向 None。因此,要检查堆栈是否为空,我们只需检查 top 是否指向 None 或者 stackSize 变量的值是否为 0。我们可以实现 isEmpty()方法来检查堆栈是否为空,如下所示。
def isEmpty(self):
if self.stackSize==0:
return True
else:
return False
使用 python 中的链表实现堆栈的完整工作代码如下。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 25 00:28:19 2021
@author: aditya1117
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class Stack:
def __init__(self):
self.top=None
self.stackSize=0
def push(self,data):
temp=Node(data)
if self.top is None:
self.top=temp
self.stackSize= self.stackSize+1
else:
temp.next=self.top
self.top=temp
self.stackSize=self.stackSize+1
def pop(self):
try:
if self.top == None:
raise Exception("Stack is Empty")
else:
temp=self.top
self.top=self.top.next
tempdata=temp.data
self.stackSize= self.stackSize-1
del temp
return tempdata
except Exception as e:
print(str(e))
def isEmpty(self):
if self.stackSize==0:
return True
else:
return False
def size(self):
return self.stackSize
def top_element(self):
try:
if self.top == None:
raise Exception("Stack is Empty")
else:
return self.top.data
except Exception as e:
print(str(e))
s=Stack()
s.push(1)
print(s.size())
s.push(2)
print(s.size())
print(s.pop())
print(s.size())
print(s.pop())
print(s.stackSize)
print(s.top_element())
print(s.isEmpty())
输出:
1
2
2
1
1
0
Stack is Empty
None
True
结论
在本文中,我们使用 python 中的链表实现了 stack 及其所有操作。为了更深入地了解它,并理解 stack 与内置数据结构(如 python dictionary 、list 和 set)有何不同,复制上面示例中给出的完整代码,并试验其中的操作。请继续关注更多内容丰富的文章。
将 Python 文件导入 Python 中的程序
原文:https://www.pythonforbeginners.com/basics/import-python-file-into-a-program-in-python
在 python 中,我们通过导入不同的内置库来执行大部分任务。在这篇文章中,我们将讨论如何将一个 python 文件导入到一个 python 程序中。
从当前工作目录导入文件
我们可以使用任何文件作为模块来导入代码。为此,我们将使用 import 语句。例如,假设我们在当前工作目录中有以下名为sample_module.py的文件。

sample_module.py 中的代码如下。
def print_module_name():
print("Hi, I am in the sample module file.")
为了导入 sample_module.py 定义的函数,我们可以使用下面的语句简单地导入 sample_module.py。
import sample_module
在这里,您可以观察到我们在 import 语句中只写了文件名,而没有写文件扩展名。导入文件后,您可以使用 python 文件中定义的函数,如下所示。
import sample_module
print("I am in example file. Calling functions from imported file.")
sample_module.print_module_name()
输出:
I am in example file. Calling functions from imported file.
Hi, I am in the sample module file.
将文件从不同的目录导入 Python 程序
任何 python 程序都可以直接从某些目录导入模块。这些目录在文件路径中定义。要查看这些目录,我们可以使用 sys 模块。sys 模块中的 path 属性包含当前 python 程序可以从中导入其他模块的所有目录的名称。您可以使用如下所示的sys.path属性打印所有这样的目录。
import sys
print(sys.path)
输出:
['/home/aditya1117/import python example', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/aditya1117/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.10/dist-packages']
如果任何目录的文件路径出现在sys.path属性中,我们可以将模块从该目录直接导入到我们的 python 文件中。您可以看到当前的工作目录 "import python example"出现在sys.path列表中。这就是我们能够将 sample_module 文件直接导入程序的原因。
因此,要从另一个目录导入文件,我们首先必须将该目录的文件路径添加到sys.path属性中。我们知道sys.path属性包含一个文件路径列表,我们可以使用append()方法将目录的文件路径附加到 python 列表中。在将目录的文件路径添加到sys.path属性之后,我们可以将目录中定义的 python 文件导入到我们当前的 python 程序中。
您可以在下面的示例中观察到这一点。
import sys
print("Hi, I am in example file.")
print(sys.path)
sys.path.append("/home/aditya1117/codes")
print("New file paths:")
print(sys.path)
import sample
sample.module_name_printer()
输出:
Hi, I am in example file.
['/home/aditya1117/import python example', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/aditya1117/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.10/dist-packages']
New file paths:
['/home/aditya1117/import python example', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/aditya1117/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.10/dist-packages', '/home/aditya1117/codes']
Hi, I am in sample.py file in \codes directory.
结论
在本文中,我们讨论了如何将 python 文件导入 python 程序。要了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的文件处理的文章。你可能也会喜欢这篇关于用 python 理解列表的文章。
Python 中的有序树遍历
原文:https://www.pythonforbeginners.com/data-structures/in-order-tree-traversal-in-python
你可能研究过遍历一个 python 字典、一个列表或者一个元组的算法。在本文中,我们将研究遍历二叉树的有序遍历算法。我们还将讨论算法的实现。
什么是有序树遍历算法?
有序树遍历算法是一种深度优先遍历算法。这意味着我们先遍历节点的子节点,然后再遍历它的兄弟节点。这样,我们遍历到最大深度,打印元素直到最后一个节点,然后回到顶部打印其他元素。
该算法被称为按序遍历算法,因为当我们使用该算法遍历二叉查找树时,树的元素按其值的升序打印。
有序遍历算法
我们知道,在二叉查找树中,任何节点的左子节点包含一个小于当前节点的元素,而节点的右子节点包含一个大于当前节点的元素。因此,为了按顺序打印元素,我们必须首先打印左边的子节点,然后是当前节点,最后是右边的子节点。这个相同的规则将用于打印树的每个节点。
我们将从根节点开始,遍历当前节点的左子树或左子树,然后遍历当前节点。最后,我们将遍历当前节点的右子树。我们将递归地执行这个操作,直到遍历完所有节点。
为了更好地理解这个概念,让我们使用一个示例二叉查找树,并使用有序二叉树遍历算法遍历它。

In-order Tree traversal
这里,我们将从根节点 50 开始。在打印 50 之前,我们必须遍历 50 的左子树。所以,我们要去 20 号。在打印 20 之前,我们必须遍历 20 的左子树。所以,我们要去 11 号。由于 11 没有子级,我们将打印 11 并向上移动到 20。打印完 20 之后,我们将遍历 20 的右子树。由于 22 没有孩子,我们将打印 22 并向上移动到 50。在 50,它的左子树已经被遍历,所以我们将打印 50。之后,我们将使用相同的过程遍历 50 的右子树。全树的有序遍历是:11,20,22,50,52,53,78。
有序树遍历在 Python 中的实现
有序树遍历的算法可以用公式表示如下。
- 递归遍历左边的子树。
- 打印根节点。
- 递归遍历右边的子树。
这里,我们只打印节点中的元素,如果它是一个叶节点或者它的左子树中的所有元素都已经被打印。
我们现在将在 python 中实现上述算法,并对上述示例中给出的二叉查找树执行该算法。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def inorder(root):
# if root is None,return
if root == None:
return
# traverse left subtree
inorder(root.leftChild)
# print the current node
print(root.data, end=" ,")
# traverse right subtree
inorder(root.rightChild)
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# 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
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
print("Inorder traversal of the binary tree is:")
inorder(root)
输出:
Inorder traversal of the binary tree is:
11 ,20 ,22 ,50 ,52 ,53 ,78 ,
结论
在本文中,我们讨论了 Python 中的有序树遍历算法。在接下来的文章中,我们将实现其他的树遍历算法,比如前序树遍历和后序树遍历算法。要了解更多关于其他数据结构的知识,可以阅读这篇关于 Python 中的链表的文章。


浙公网安备 33010602011771号