You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python处理章节编号列表:非首段数值减7适配多位数字

书卷章节节号偏移处理实现方案

实现思路

核心是通过正则精准匹配字符串结构,完全保留原字符串里书卷号部分、空格、首尾格式不变,仅提取章节号、节号的数字部分做减7运算,兼容任意位数数字、带不规则空格的输入场景,遇到格式异常的条目自动原样保留不中断运行。

完整实现代码

import re

# 正则匹配规则:自动捕获书卷前缀、章节数字、节数字、尾部内容,不破坏原有空格格式
VERSE_PATTERN = re.compile(r'^(.*?\.)(-?\d+)\.(-?\d+)(.*?)$')

def process_verse_list(verse_list, offset=-7):
    processed = []
    for entry in verse_list:
        match_res = VERSE_PATTERN.match(entry.rstrip('\n'))
        if not match_res:
            # 格式不匹配的条目直接保留原值
            processed.append(entry)
            continue
        book_prefix, chapter_num, verse_num, suffix = match_res.groups()
        # 数值计算后拼接回原格式
        new_chapter = str(int(chapter_num) + offset)
        new_verse = str(int(verse_num) + offset)
        processed.append(f"{book_prefix}{new_chapter}.{new_verse}{suffix}")
    return processed


# 以下是原有的书卷列表生成代码
chapter_count_book_a = 20
verse_count_book_a = [100] * 20

def get_book_data(book, chapter_count, verse_count):
    if chapter_count != len(verse_count):
        print("ERROR!!!")
    answer = []
    for chapter in range(chapter_count):
        chp = f"{book}.{chapter+1}"
        verse_total = verse_count[chapter]
        for verse in range(verse_total):
            answer.append(f"{chp}.{verse+1}")
    return answer

book_a_data = get_book_data("66", chapter_count_book_a, verse_count_book_a)
# 调用处理即可得到偏移后的结果
processed_book_a = process_verse_list(book_a_data)

# 示例输入测试
if __name__ == "__main__":
    test_input = ['66 .1.1 ', '66 .1.2', '66 .2.1 ', '66 .2.2', '66 .3.1 ', '66 .3.2','66.22.1']
    print(process_verse_list(test_input))
    # 输出结果与预期完全一致:['66 .-6.-6 ', '66 .-6.-5', '66 .-5.-6 ', '66 .-5.-5', '66 .-4.-6 ', '66 .-4.-5', '66.15.-6']

方案特性

  • 完全保留原始字符串的格式:包括书卷号和分隔点之间的空格、字符串首尾的空格都不会被修改
  • 兼容任意长度数字:1位、2位、3位甚至带负号的数字都可以正确识别计算
  • 容错性强:遇到不符合「书卷号.章节号.节号」结构的异常条目会直接原样保留,不会抛出异常中断程序
  • 偏移量可配置:如果后续需要调整减去的数值,只需要修改offset参数即可,比如要减10就传入offset=-10

内容的提问来源于stack exchange,提问作者John Beats

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 12:25:18