行缩进与取消缩进算法问题:Python代码无法格式化列表文本
代码错误排查与修正方案
原代码存在的核心问题
缩进逻辑完全颠倒
原代码中,当遇到和bullet_point相同符号的行时会减少缩进,这和实际需求完全相反。比如• Lower limb examination:触发加缩进后,后续的-行因为符号不同不会触发缩进,反而再次出现•行(如• Feet:)时才会减少缩进,导致层级混乱。列表符号识别不全面
仅通过len(line.split(" ")[0])==1判断列表项,既没覆盖所有列表符号(•、-、o),还会误判类似2.的章节标题,导致子列表项无法被正确识别。层级管理混乱
直接用字符串累加/截断add_indent来管理缩进,没有跟踪明确的层级深度,遇到嵌套子列表(如ROM:下的o行)时,无法正确增加缩进,导致层级错误。状态重置不彻底
空行仅重置了add_indent,但bullet_point未同步重置,可能影响后续章节的层级判断。
修正后的代码
paragraph = ''' • Mobilising independently with a 4-wheel walker • Gait: Good quality with good cadence, good step length, and adequate foot clearance • Lower limb examination: - Tone: Normal bilaterally - No clonus in either leg - Passive dorsiflexion: Possible to -10 to -5 degrees bilaterally - Power: 5/5 in all major muscle groups of lower limbs bilaterally - Sensation: Intact to gross touch bilaterally - ROM: o Right hip flexion: 0-120 degrees o Left hip flexion: 10-120 degrees (fixed flexion deformity present) • Feet: Not broad-based 2. Post-stroke mobility and spasticity • Improvement noted in right leg stiffness • Continuing with current exercise regimen: - Neuro Group twice weekly - Gym group (including bike riding) - Home exercises • Plan: - Continue current exercise programme - Maintain current baclofen dose ''' # 定义所有列表符号 LIST_BULLETS = {'•', '-', 'o'} current_level = 0 corpus = [] prev_bullet = None for line in paragraph.splitlines(): stripped_line = line.strip() if not stripped_line: # 空行重置所有状态 current_level = 0 prev_bullet = None corpus.append(line) continue # 识别当前行的列表符号 current_bullet = None for bullet in LIST_BULLETS: if stripped_line.startswith(bullet): current_bullet = bullet break # 处理章节标题(如2.开头的行) if not current_bullet and stripped_line[0].isdigit() and '.' in stripped_line.split()[0]: current_level = 0 prev_bullet = None corpus.append(line) continue if current_bullet: # 处理带冒号的父级列表项 if stripped_line.endswith(':'): corpus.append(' ' * current_level + stripped_line) current_level += 1 prev_bullet = current_bullet else: # 根据符号优先级判断是否回退层级 bullet_order = {'•':0, '-':1, 'o':2} if prev_bullet and bullet_order[current_bullet] < bullet_order[prev_bullet]: current_level = bullet_order[current_bullet] + 1 # 添加当前层级的缩进 corpus.append(' ' * (current_level - 1) + stripped_line) prev_bullet = current_bullet else: corpus.append(line) # 输出格式化后的内容 for line in corpus: print(line)
修正逻辑说明
- 明确定义所有列表符号,避免漏判;
- 用
current_level跟踪层级深度,每个层级对应2个空格,比直接操作字符串更清晰; - 遇到带
:的列表项时,自动提升层级,后续子项使用对应缩进; - 通过符号优先级(
•>->o)判断是否需要回退层级,确保同级列表项回到正确缩进; - 空行和章节标题会彻底重置层级状态,避免影响后续内容。
内容的提问来源于stack exchange,提问作者Legion
相关产品推荐
相关产品推荐

