Python代码自动格式化:字典

3

我有一个极其混乱的Python源代码文件,它由无数个未经缩进的字典组成。

这个文件根本无法阅读。我想要重新格式化这个文件,让它看起来像这样:

[
    {
        'foo'     : 'bar',
        'alpha'   : 'beta',
        'long key': 'bla'
    }

    # 93457823 more dictionaries
]

请注意对齐的冒号及易于理解的缩进。

有没有工具可以实现这个功能?


1
PyCharm怎么样?也许你无法得到完全符合你喜好的缩进,但这是一个开始... - brunsgaard
它不会对冒号进行对齐,但是您可以使用“json.dumps(obj,indent=4)”进行格式化。 - jonrsharpe
数据有多复杂?如果所有数据都可以被JSON序列化,你可以使用JSON来美观地打印它。 - BrenBarn
2个回答

1
在Python中,有一个PEP8标准用于规定代码应该如何格式化。还有一种工具可以强制执行这个标准,即 "pep8"。

https://pypi.python.org/pypi/autopep8/

从文档中得知以下混乱的代码:
import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3(   object ):
    def __init__    ( self, bar ):
     #Comments should have a space after the hash.
     if bar : bar+=1;  bar=bar* bar   ; return bar
     else:
                    some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
                    return (sys.path, some_string)    import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3(   object ):
    def __init__    ( self, bar ):
     #Comments should have a space after the hash.
     if bar : bar+=1;  bar=bar* bar   ; return bar
     else:
                    some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
                    return (sys.path, some_string)

转换为:

转换为:

import math
import sys


def example1():
    # This is a long comment. This should be wrapped to fit within 72
    # characters.
    some_tuple = (1, 2, 3, 'a')
    some_variable = {
        'long': 'Long code lines should be wrapped within 79 characters.',
        'other': [
            math.pi,
            100,
            200,
            300,
            9876543210,
            'This is a long string that goes on'],
        'more': {
            'inner': 'This whole logical line should be wrapped.',
            some_tuple: [
                1,
                20,
                300,
                40000,
                500000000,
                60000000000000000]}}
    return (some_tuple, some_variable)


def example2():
    return ('' in {'f': 2}) in {'has_key() is deprecated': True}


class Example3(object):

    def __init__(self, bar):
        # Comments should have a space after the hash.
        if bar:
            bar += 1
            bar = bar * bar
            return bar
        else:
            some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
            return (sys.path, some_string)

虽然 PEP 8 明确禁止像 OP 想要的那样对齐元素,但这可能是最好的选择。 - user395760
我明确地想要对齐它们 :( 键的长度差异太大了。 - salezica

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接