Python代码写得丑怎么办?推荐几个神器拯救你
本文推荐几个神器来拯救奇丑无边的python代码。
一、Jupyter notebook 篇
Jupyter notebook的代码要想写得规范,推荐用Code prettify插件。
安装插件
首先插件Nbextensions
执行以下命令
pip install jupyter_contrib_nbextensions
无报错再执行:
jupyter contrib nbextension install --user
选取Code prettify模块
备注:需要安装 yapf模块
pip install yapf


使用如下:
原始不规范代码:

使用工具栏最右侧的按钮:

使用后代码立刻变规范了:

二、Pycharm篇
2.1PyCharm集成pylint
pylint是代码检查工具,不能自动修改代码
Pylint 安装
pip install pylint
PyCharm 设置
文件(file)-设置(settings)-外部工具(external-tools)-添加,其中:
program:
是python安装路径下的Scripts路径,我的是(建议搜索pylint.exe找到路径)
C:ProgramDataAnaconda3Scriptspylint.exe
Arguments:
--reports=n --disable=C0103 $FilePath$
(最后必须以$FilePath$结尾)
working directory:
$FileDir$
(必须是这个)
output filters:
$FILE_PATH$:$LINE$:
具体配置如图:

配置完毕,选择一个Python程序,右键点击,快捷菜单中会有“Extensions Tools -> Pylint”,点击运行即可。输出结果在执行程序结果的窗口(IDE下半部分)。
如果看到返回值为0,说明程序没问题了。
2.2 autopep8
autopep8是一款将python代码自动排版为PEP8风格的工具
autopep8安装
pip install autopep8
autopep8配置
文件(file)-设置(settings)-外部工具(external-tools)-添加,其中:
Name:
autopep8
(起名而已,随便起)
Program: autopep8
Arguments:
--in-place --aggressive --aggressive $FilePath$
Working directory:
$ProjectFileDir$
Output filters:
$FILE_PATH$:$LINE$:$COLUMN$:.*
具体配置如图:

将鼠标放在该文件的编辑器中→右键→External Tools→点击Autopep8。这样你的代码就符合pep8的风格了。
使用效果如下:
原始不规范代码:

使用工具后:

三、变量命名篇
在平时工作中,好多程序员都在为变量的命名纠结不已,随便命名怕以后看不懂,想好好命名可是自己的英文水平又不好,在这个命名上可能需要花费大量的时间,会耽误到开发的效率,今天推荐一个神器,这个神器可以摆脱变量命名纠结!
工具网址
GitHub 链接:

输入要起名的变量,可以是中文或者英文。
点击搜索后,网站会给出变量名的翻译,下方给出变量的起名建议,大家可以copy下变量名,也可以看下用了这个变量的源代码,而且可以选择开发语言种类。
点击「Search」就是基于当前命名搜索其它相关的命名。
点击「Repo」就是链接到使用该命名的代码所在的资源库。
点击「Copy」是复制该命名。
点击「Codes」可以查看使用命名的示例代码。
需要python教程+PDF电子书的小伙伴
请关注、转发、私信我"学习"就能免费获取教程+电子书。
