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

如何用Python为Markdown中的列表标题添加粗体格式?

为列表标题添加粗体的实现方法

核心思路

通过正则表达式匹配所有符合特征的列表标题(有序列表开头如1. 、无序列表开头如* 或+ ,且以冒号结尾),然后为匹配内容添加粗体格式。

具体步骤

  • 编写正则匹配规则
    使用以下正则表达式匹配目标行:

    ^((?:\d+\.|\*|\+)\s*.+?:)
    

    规则说明:

    • ^:匹配行的起始位置
    • (?:\d+\.|\*|\+):匹配有序列表标记(数字+句号)或无序列表标记(*或+),不捕获该部分
    • \s*:匹配标记后的任意空白字符
    • .+?::匹配到冒号为止的标题内容
    • 整个括号内的内容会被捕获,用于后续替换
  • Python代码实现替换
    使用re.sub()函数执行替换操作,将捕获的内容用粗体标记包裹:

    import re
    
    text = '<div style="padding: 10px; border: 1px solid #e5e7eb; font-size: .95rem; border-radius: 8px"><h3>Income Statement</h3>
    
    1. Total Revenue:
    
    The total revenue for xxxx for the year ended December 31, 2022 was $xxxxx million.
    
    2. Revenue by Source:
    
    The breakdown of xxxx\'s revenue by source for the year ended December 31, 2022 is as follows:
    
    * Billboard:
    	+ Static displays: $xxxx.x million
    	+ Digital displays: $xxxx million
    	+ Other: $xxx million
    	Total billboard revenues: $xxxx million
    * Transit:
    	+ Static displays: $xxxx million
    	+ Digital displays: $xxxxx million
    	+ Other: $xxx million
    	Total transit revenues: $xxxxxxxxx million
    * Sports marketing and other: $xxxxx million
    
    Total revenues: $xxxxx million
    
    </div>'
    
    # 替换为Markdown粗体格式
    updated_text = re.sub(r'^((?:\d+\.|\*|\+)\s*.+?:)', r'**\1**', text, flags=re.MULTILINE)
    
    # 若需HTML粗体格式,可替换为:
    # updated_text = re.sub(r'^((?:\d+\.|\*|\+)\s*.+?:)', r'<strong>\1</strong>', text, flags=re.MULTILINE)
    
    print(updated_text)
    
  • 替换效果示例
    处理后符合条件的标题会变为粗体:

    1. Total Revenue:

    The total revenue for xxxx for the year ended December 31, 2022 was $xxxxx million.

    2. Revenue by Source:

    The breakdown of xxxx's revenue by source for the year ended December 31, 2022 is as follows:

    * Billboard:
    + Static displays: $xxxx.x million
    + Digital displays: $xxxx million
    + Other: $xxx million
    Total billboard revenues: $xxxx million

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:05:33