在Python中循环时更新列表时出错

问题描述 投票:0回答:1

为什么列表“spans”从未更新?我不明白为什么代码会陷入无限循环。

PDF:https://www.sil.org/system/files/reapdata/62/99/18/62991811720566250411942290005522370655/40337_02.pdf

“块”示例:https://jumpshare.com/s/y393JOBQJfIyE51Gkexn

import fitz

doc = fitz.open("cubeo/40337_02.pdf")
page = doc[3]

blocks = page.get_text("dict", flags = fitz.TEXTFLAGS_TEXT)["blocks"]
for block in blocks: 
    entries = []
    if len(block["lines"]) > 3: # ignora legendas e número de página
        for line in block["lines"]: 
            spans = []
            for span in line["spans"]:
                spans.append({"text": span["text"].replace("�", " "), "size": int(span["size"]), "font": span["font"]})

            # While there are spans left
            while True:
                # Delimits where an entry starts
                entry_first_position = None
                for i, span in enumerate(spans):
                    if span["font"] == "Sb&cuSILCharis-Bold":
                        entry_first_position = i
                        break
                if entry_first_position is not None:
                    # Delimits where an entry ends
                    entry_last_position = None
                    for i, span in enumerate(spans[entry_first_position:], start=entry_first_position):
                        if span["font"] == "Sb&cuSILCharis-Bold":
                            entry_last_position = i
                            break
                    if entry_last_position is not None:
                        # Whole entry is added as a list
                        append_list = spans[entry_first_position:entry_last_position]
                        entries.append(append_list)
                        spans = spans[:entry_first_position] + spans[entry_last_position:]
                    else:
                        break
                else:
                    break
             print(spans)

我期望的是 print(spans) 输出“[]”。然而,代码永远不会达到这一点。

python loops pymupdf
1个回答
0
投票
for i, span in enumerate(spans[entry_first_position:], start=entry_first_position):

不会跳过

span["font"] == "Sb&cuSILCharis-Bold"
的第一场比赛。所以
entry_last_position == entry_first_position
,什么都没有被删除,你陷入了无限循环。将其更改为

for i, span in enumerate(spans[entry_first_position+1:], start=entry_first_position+1):

因此它从列表中的下一个位置开始查找

© www.soinside.com 2019 - 2024. All rights reserved.