尝试修复因LLM多写/少写括号导致的不平衡结构。 参数: text: 原始JSON文本 返回: Tuple[str, bool]: (修复后的文本, 是否有修改)
(self, text: str)
| 509 | return text |
| 510 | |
| 511 | def _balance_brackets(self, text: str) -> Tuple[str, bool]: |
| 512 | """ |
| 513 | 尝试修复因LLM多写/少写括号导致的不平衡结构。 |
| 514 | |
| 515 | 参数: |
| 516 | text: 原始JSON文本 |
| 517 | |
| 518 | 返回: |
| 519 | Tuple[str, bool]: (修复后的文本, 是否有修改) |
| 520 | """ |
| 521 | if not text: |
| 522 | return text, False |
| 523 | |
| 524 | result: List[str] = [] |
| 525 | stack: List[str] = [] |
| 526 | mutated = False |
| 527 | in_string = False |
| 528 | escaped = False |
| 529 | |
| 530 | opener_map = {"{": "}", "[": "]"} |
| 531 | |
| 532 | for ch in text: |
| 533 | if escaped: |
| 534 | result.append(ch) |
| 535 | escaped = False |
| 536 | continue |
| 537 | |
| 538 | if ch == "\\": |
| 539 | result.append(ch) |
| 540 | escaped = True |
| 541 | continue |
| 542 | |
| 543 | if ch == '"': |
| 544 | result.append(ch) |
| 545 | in_string = not in_string |
| 546 | continue |
| 547 | |
| 548 | if in_string: |
| 549 | result.append(ch) |
| 550 | continue |
| 551 | |
| 552 | if ch in "{[": |
| 553 | stack.append(ch) |
| 554 | result.append(ch) |
| 555 | continue |
| 556 | |
| 557 | if ch in "}]": |
| 558 | if stack and ( |
| 559 | (ch == "}" and stack[-1] == "{") or (ch == "]" and stack[-1] == "[") |
| 560 | ): |
| 561 | stack.pop() |
| 562 | result.append(ch) |
| 563 | else: |
| 564 | # 不匹配的闭括号,忽略 |
| 565 | mutated = True |
| 566 | continue |
| 567 | |
| 568 | result.append(ch) |
no test coverage detected