消除Python中的缩进

2024-05-16 11:54:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用GoogleDocsAPI检索文档的内容,并使用Python对其进行处理。但是,文档的结构很复杂,我必须遍历返回的JSON的多个节点,因此我必须使用multiple for loops来获取所需的内容并进行必要的过滤。有没有办法消除一些缩进,使格式看起来更有条理

以下是我的循环片段:

for key, docContent in docs_api_result.json().items():
    if key == "body":
        content = docContent['content']
        for i, body_content in enumerate(content):
            if "table" in body_content:
                for sKey, tableContent in content[i]['table'].items():
                    if sKey == "tableRows":
                        for tableRowContent in tableContent:
                            for tableCellMain in tableRowContent['tableCells']:
                                for tableCellContent in tableCellMain['content']:
                                    hasBullet = False
                                    for tableCellElement in tableCellContent['paragraph']['elements']:
                                        if "bullet" in tableCellContent['paragraph']:
                                            ...

我知道,我没有

if True:
    # some code here

我可以换成

if False:
    continue
# some code here

删除一些缩进,但这只能解决部分问题。我还有7个for循环,我希望我也能去掉一些凹痕

感谢您的帮助!:)


Tags: keyin文档内容foriftableitems
2条回答

我对python没有太多的经验,但我非常确信,每次缩进只能使用一个空格,而不是四个空格的倍数,而且不会出现缩进错误。虽然它不符合PEP 8协议。。。 因此,只需删除这组代码中每4个空格/制表符,即1个空格

减少缩进级别的一般方法是识别代码块以用于它们自己的函数

例如,看着你的循环,我想我会尝试以下方法:

class ApiResultProcessor(object):
    def process_api_result(self, api_result):
        doc_dict = api_result.json()
        if "body" in doc_dict:
            self.process_body(doc_dict["body"])

    def process_body(self, body_dict):
        content = body_dict["content"]
        for i, content_element_dict in enumerate(content):
            if "table" in content_element_dict:
                self.process_table(content_element_dict["table"])
        ...
    

    def process_table(self, table_dict):
        for tableRowContent in table_dict["tableRows"]:
            for tableCellMain in tableRowContent["tableCells"]:
                for tableCellContent in tableCellMain['content']:
                    self.process_cell_content(tableCellContent)

    def process_cell_content(self, table_cell_dict):
        hasBullet = False
        for tableCellElement in table_cell_dict["paragraph"]["elements"]:
            if "bullet" in table_cell_dict["paragraph"]:
                ...

我所做的唯一重构就是试图避免可怕的"for if" antipattern

相关问题 更多 >