如何修正TTP模板,实现含列表项的多分段文本精准解析?
问题:修正模板实现分段列表项匹配
输入文本
**Section 1** Description1 1. Foo 2. Bar **Section 2** Description2 1. NotFoo 2. NotBar 3. NotFooBar
当前使用的模板
section1Template = """ <group name = "Section1"> 1. {{ item1 | ORPHRASE }} </group> """ section2Template = """ <group name = "Section2"> 1. {{ item2 | ORPHRASE }} </group> """ combinedTemplate = f""" {section1Template} {section2Template} """
预期输出
[ { 'section1': [{'item1': 'Foo', 'item1': 'Bar'}], 'section2': [{'item2': 'NotFoo', 'item2': 'NotBar', 'item2': 'NotFooBar'}] } ]
实际输出
[ { 'section1': [{'item1': 'Foo', 'item1': 'Bar', 'item1': 'NotFoo', 'item1': 'NotBar', 'item1': 'NotFooBar'}], 'section2': [{'item2': 'Foo', 'item2': 'Bar', 'item2': 'NotFoo', 'item2': 'NotBar', 'item2': 'NotFooBar'}] } ]
修正方案
问题根源在于当前模板的分组未绑定对应分段的上下文,导致所有列表项被全局捕获,跨分段污染结果。需要让每个分组严格限定在对应Section的内容范围内,只捕获该分段下的列表项。
修正后的模板如下:
section1Template = """ <group name="Section1"> **Section 1** Description1 {{#repeat}} 1. {{item1 | ORPHRASE}} {{/repeat}} </group> """ section2Template = """ <group name="Section2"> **Section 2** Description2 {{#repeat}} 1. {{item2 | ORPHRASE}} {{/repeat}} </group> """ combinedTemplate = f""" {section1Template} {section2Template} """
修正说明
- 每个分组先明确匹配对应Section的标题和描述,将分组的上下文限定在该分段内;
- 使用
{{#repeat}}语法(对应模板引擎的循环捕获逻辑),批量捕获该分段下的所有列表项,确保只获取当前Section内的条目,不会交叉捕获其他分段的内容。
内容的提问来源于stack exchange,提问作者Matt T
相关产品推荐
相关产品推荐

