这些Python代码技巧,你可能还不知道!
优采云 发布时间: 2022-06-03 11:00这些Python代码技巧,你可能还不知道!
它可以帮助你从大量顶级国际出版物中检索到新闻文章和相关元数据。你可以检索图像、文本和作者名。
它还有一些内置的 NLP 功能。
地址:#performing-nlp-on-an-article
如果你想在下一个项目中使用 BeautifulSoup 或其它 DIY 网页抓取库,那么不如使用$ pip install newspaper3k,既省时又省事,何乐而不为呢?
运算符重载(Operator overloading)
Python 支持运算符重载。
它实际上是一个简单的概念。你有没有想过为什么 Python 允许用户使用 + 运算符来将数字相加,并级联字符串?这就是运算符重载在发挥作用。
你可以使用 Python 的标准运算符号来定义对象,这样你可以在与这些对象相关的语境中使用它们。
class Thing:<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> def __init__(self, value):<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> self.__value = value<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> def __gt__(self, other):<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> return self.__value > other.__value<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> def __lt__(self, other):<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> return self.__value nothing<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /># False<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />something >> file = open('file.txt', 'r')<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />>>> print(file)<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />
这使代码 debug 变得简单很多。将字符串添加到类别定义,如下所示:
class someClass:<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> def __repr__(self):<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> return ""<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />someInstance = someClass()<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /># prints <br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />print(someInstance)
sh
Python 是一种伟大的脚本语言,不过有时使用标准 os 和 subprocess 库会有点棘手。
sh 库提供了一种不错的替代方案。
sh 库:
该库允许用户像使用普通函数一样调用任意程序,这对自动化工作流和任务非常有用。
from sh import *<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />sh.pwd()<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />sh.mkdir('new_folder')<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />sh.touch('new_file.txt')<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />sh.whoami()<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />sh.echo('This is great!')
类型提示(Type hints)
Python 是动态语言。在定义变量、函数、类别等时无需指定数据类型。
这有利于缩短开发周期。但是,简单的类型错误(typing issue)导致的运行时错误真的太烦了。
从 Python 3.5 版本开始,用户可以选择在定义函数时开启类型提示。
def addTwo(x : Int) -> Int:<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> return x + 2
你还可以定义类型别名:
from typing import List<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />Vector = List[float]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />Matrix = List[Vector]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />def addMatrix(a : Matrix, b : Matrix) -> Matrix:<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> result = []<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> for i,row in enumerate(a):<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> result_row =[]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> for j, col in enumerate(row):<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> result_row += [a[i][j] + b[i][j]]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> result += [result_row]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> return result<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />x = [[1.0, 0.0], [0.0, 1.0]]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />y = [[2.0, 1.0], [0.0, -2.0]]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />z = addMatrix(x, y)
尽管非强制,但类型注释可以使代码更易理解。
它们还允许你在运行之前使用类型检查工具捕捉 TypeError。在进行大型复杂项目时执行此类操作是值得的。
uuid
生成通用唯一标识符(Universally Unique ID,UUID)的一种快速简单方法就是使用 Python 标准库的 uuid 模块。
uuid 模块:
import uuid<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />user_id = uuid.uuid4()<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />print(user_id)
这创建了一个随机化后的 128 比特数字,该数字几乎必然是唯一的。
事实上,可以生成 2¹²²可能的 UUID。这个数字超过了 5,000,000,000,000,000,000,000,000,000,000,000,000。
在给定集合中找出重复数字的可能性极低。即使有一万亿 UUID,重复数字存在的概率也远远低于十亿分之一。
虚拟环境(Virtual environment)
这可能是 Python 中我最喜欢的事物了。
你可能同时处理多个 Python 项目。不幸的是,有时候两个项目依赖于相同依赖项的不同版本。那你要安装哪个版本呢?
幸运的是,Python 支持虚拟环境,这使得用户能够充分利用两种环境。见下列行:
python -m venv my-project<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />source my-project/bin/activate<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />pip install all-the-modules
现在你在一台机器上具备独立的多个 Python 版本了。问题解决!
wikipedia
Wikipedia 拥有一个很棒的 API,允许用户以编程方式访问巨大体量的免费知识和信息。
wikipedia 模块使得访问该 API 非常便捷。
Wikipedia 模块:
import wikipedia<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />result = wikipedia.page('freeCodeCamp')<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />print(result.summary)<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />for link in result.links:<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" /> print(link)
和真实的维基百科网站类似,该模块支持多种语言、页面消歧、随机页面检索,甚至还具备 donate() 方法。
xkcd
humour 是 Python 语言的一个关键特征,其名称来自英国喜剧片《蒙提·派森的飞行马戏团》(Monty Python and the Flying Circus)。Python 的很多官方文档引用了该喜剧片最著名的剧情。
幽默感并不限于文档。试着运行下列行:
import antigravity
将打开 xkcd 画的 Python *敏*感*词*。不要改变这一点,Python。不要改变。
YAML
YAML 代表 『YAML Ain』t Markup Language』。它是一种数据格式语言,是 JSON 的超集。
与 JSON 不同,它可以存储更复杂的对象并引用自己的元素。你还可以编写注释,使其尤其适用于编写配置文件。
PyYAML 模块()可以让你在 Python 中使用 YAML。安装:
$ pip install pyyaml
然后导入到项目中:
import yaml
PyYAML 使你能够存储任何数据类型的 Python 对象,以及任何用户定义类别的实例。
zip
给你支最后一招,非常酷。还在用两个列表来组成一部词典吗?
keys = ['a', 'b', 'c']<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />vals = [1, 2, 3]<br style="max-width: 100%;box-sizing: border-box !important;word-wrap: break-word !important;" />zipped = dict(zip(keys, vals))
zip() 内置函数使用多个可迭代对象作为输入并返回元组列表。每个元组按位置索引对输入对象的元素进行分组。
你也可以通过调用*zip() 来「解压」对象。
免责声明:本文系网络转载,版权归原作者所有。如涉及作品版权问题,请与我们联系,我们将根据您提供的版权证明材料确认版权并支付稿酬或者删除内容。