有没有办法将 Python 代码中的缩进转换为大括号? [英] Is there a way to convert indentation in Python code to braces?
问题描述
我是一个想学习 Python 的盲人程序员.不幸的是,代码块用不同级别的缩进表示这一事实是一个主要的绊脚石.我想知道是否有任何可用的工具可以让我使用大括号或其他一些代码块分隔符编写代码,然后将该格式转换为 Python 解释器可以使用的正确缩进的表示形式?
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
推荐答案
python 本身有一个解决方案可以解决您的问题.pindent.py
,它位于 Windows 安装的 ToolsScripts 目录中(我的路径是 C:Python25ToolsScripts),看起来你必须 从 svn.python.org 获取它 如果你正在运行Linux 或 OSX.
There's a solution to your problem that is distributed with python itself. pindent.py
, it's located in the ToolsScripts directory in a windows install (my path to it is C:Python25ToolsScripts), it looks like you'd have to grab it from svn.python.org if you are running on Linux or OSX.
它在块关闭时添加注释,或者如果添加注释可以正确缩进代码.以下是pindent用命令输出的代码示例:
It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command:
pindent.py -c myfile.py
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
原始 myfile.py
在哪里:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
else:
print 'oops!'
您还可以使用 pindent.py -r
根据注释插入正确的缩进(阅读 pindent.py 的标题了解详细信息),这应该允许您在 python 中编码而不必担心缩进.
You can also use pindent.py -r
to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation.
例如,运行 pindent.py -r myfile.py
会将 myfile.py
中的以下代码转换为与以下代码相同的正确缩进(也有注释)的代码由上面的 pindent.py -c
示例生成:
For example, running pindent.py -r myfile.py
will convert the following code in myfile.py
into the same properly indented (and also commented) code as produced by the pindent.py -c
example above:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
我很想知道您最终使用的是什么解决方案,如果您需要任何进一步的帮助,请在这篇文章中发表评论,我会尽力提供帮助.
I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.
这篇关于有没有办法将 Python 代码中的缩进转换为大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!