word特定文本内容字体加粗

将带序号的一行内容加粗;
将一行中冒号前面的内容加粗。

from docx import Document
import re

def make_text_bold_with_numbering(docx_path):
    """
    将Word文档中满足以下条件的文本设置为粗体:
    1. 每个冒号前面同一行的文本内容
    2. 以序号开头的整行文本(如 1. 2. 3. 等)
    
    Args:
        docx_path (str): Word文档的路径
    """
    try:
        # 打开文档
        doc = Document(docx_path)
        
        # 遍历所有段落
        for paragraph in doc.paragraphs:
            text = paragraph.text.strip()
            
            if not text:  # 跳过空段落
                continue
            
            # 检查是否是序号开头的行
            if is_numbered_line(text):
                make_entire_paragraph_bold(paragraph)
            # 检查是否包含冒号
            elif ':' in text or ':' in text:
                process_colon_paragraph(paragraph)
        
        # 保存修改后的文档
        output_path = docx_path.replace('.docx', '_formatted.docx')
        doc.save(output_path)
        print(f"处理完成!修改后的文件已保存为: {output_path}")
        
    except FileNotFoundError:
        print(f"错误:找不到文件 {docx_path}")
    except Exception as e:
        print(f"处理文件时发生错误:{str(e)}")

def is_numbered_line(text):
    """
    检查文本是否以序号开头
    支持的格式:
    - 1. 2. 3. ... (数字+点)
    - 1) 2) 3) ... (数字+右括号)
    - (1) (2) (3) ... (括号+数字+括号)
    - 一、二、三、... (中文数字+顿号)
    - 第一章、第二章、... (第+数字+章节)
    - A. B. C. ... (字母+点)
    - I. II. III. ... (罗马数字+点)
    """
    # 去除开头的空白字符
    text = text.lstrip()
    
    # 定义各种序号模式
    patterns = [
        r'^\d+\.',           # 1. 2. 3.
        r'^\d+\)',           # 1) 2) 3)
        r'^\(\d+\)',         # (1) (2) (3)
        r'^[一二三四五六七八九十百千万]+[、。]',  # 一、二、三、
        r'^第[一二三四五六七八九十百千万\d]+[章节条款项部分]',  # 第一章、第二节
        r'^[A-Za-z]\.',      # A. B. C. 或 a. b. c.
        r'^[IVXLCDMivxlcdm]+\.',  # I. II. III. 或 i. ii. iii.
        r'^\d+\.\d+',        # 1.1 1.2 2.1 (多级序号)
        r'^\d+\.\d+\.\d+',   # 1.1.1 1.1.2 (三级序号)
    ]
    
    # 检查是否匹配任何序号模式
    for pattern in patterns:
        if re.match(pattern, text):
            return True
    
    return False

def make_entire_paragraph_bold(paragraph):
    """
    将整个段落设置为粗体
    
    Args:
        paragraph: Word文档的段落对象
    """
    for run in paragraph.runs:
        run.bold = True

def process_colon_paragraph(paragraph):
    """
    处理包含冒号的段落,将冒号前的文本设置为粗体
    
    Args:
        paragraph: Word文档的段落对象
    """
    text = paragraph.text
    
    # 清空段落内容
    paragraph.clear()
    
    # 使用正则表达式处理冒号前的文本
    # 匹配从行首到冒号的文本
    pattern = r'([^\n\r]*?)([::])'
    
    last_end = 0
    for match in re.finditer(pattern, text):
        # 添加冒号前的普通文本(如果有的话)
        before_match = text[last_end:match.start()]
        if before_match:
            paragraph.add_run(before_match)
        
        # 添加冒号前的文本(粗体)
        text_before_colon = match.group(1)
        
        # 找到这一行的开始位置
        line_start_pos = text.rfind('\n', 0, match.start()) + 1
        actual_text_before_colon = text[line_start_pos:match.start() + len(match.group(1))]
        line_text_before_colon = actual_text_before_colon[actual_text_before_colon.rfind('\n') + 1:]
        
        if line_text_before_colon.strip():
            bold_run = paragraph.add_run(line_text_before_colon)
            bold_run.bold = True
        
        # 添加冒号
        colon_run = paragraph.add_run(match.group(2))
        
        last_end = match.end()
    
    # 添加剩余文本
    remaining_text = text[last_end:]
    if remaining_text:
        paragraph.add_run(remaining_text)

def enhanced_process_colon_paragraph(paragraph):
    """
    增强版冒号处理函数 - 更精确地处理冒号前的文本
    """
    full_text = paragraph.text
    
    # 如果没有冒号,直接返回
    if ':' not in full_text and ':' not in full_text:
        return
    
    # 清空段落
    paragraph.clear()
    
    # 按行分割文本
    lines = full_text.split('\n')
    
    for i, line in enumerate(lines):
        if i > 0:  # 添加换行符(除了第一行)
            paragraph.add_run('\n')
        
        # 检查当前行是否包含冒号
        if ':' in line or ':' in line:
            # 找到第一个冒号的位置
            colon_pos_en = line.find(':')
            colon_pos_cn = line.find(':')
            
            if colon_pos_en == -1:
                colon_pos = colon_pos_cn
                colon_char = ':'
            elif colon_pos_cn == -1:
                colon_pos = colon_pos_en
                colon_char = ':'
            else:
                if colon_pos_en < colon_pos_cn:
                    colon_pos = colon_pos_en
                    colon_char = ':'
                else:
                    colon_pos = colon_pos_cn
                    colon_char = ':'
            
            # 分割文本
            text_before_colon = line[:colon_pos]
            text_after_colon = line[colon_pos + 1:]
            
            # 添加冒号前的文本(粗体)
            if text_before_colon.strip():
                bold_run = paragraph.add_run(text_before_colon)
                bold_run.bold = True
            
            # 添加冒号
            paragraph.add_run(colon_char)
            
            # 添加冒号后的文本
            if text_after_colon:
                paragraph.add_run(text_after_colon)
        else:
            # 没有冒号的行,直接添加
            paragraph.add_run(line)

def main():
    """
    主函数
    """
    file_path = "AI_zero2hero20250606.docx"
    
    print("开始处理Word文档...")
    print(f"目标文件: {file_path}")
    print("处理规则:")
    print("1. 冒号前面同一行的文本 → 粗体")
    print("2. 序号开头的整行文本 → 粗体")
    print("   支持格式: 1. 2. 3. / 1) 2) 3) / (1) (2) (3) / 一、二、三、/ A. B. C. 等")
    print("-" * 50)
    
    make_text_bold_with_numbering(file_path)

# 测试函数
def test_numbering_detection():
    """
    测试序号检测功能
    """
    test_cases = [
        "1. 这是第一项",
        "2) 这是第二项", 
        "(3) 这是第三项",
        "一、第一章内容",
        "第二节 重要内容",
        "A. 选项A",
        "I. 罗马数字一",
        "1.1 子项目",
        "1.1.1 三级项目",
        "   4. 带空格的序号",
        "这不是序号",
        "问题: 这里有冒号",
    ]
    
    print("测试序号检测功能:")
    for test_text in test_cases:
        is_numbered = is_numbered_line(test_text)
        print(f"'{test_text}' → {'是序号' if is_numbered else '不是序号'}")

if __name__ == "__main__":
    # 检查库安装
    try:
        from docx import Document
        print("python-docx 库已安装")
    except ImportError:
        print("请先安装 python-docx 库:")
        print("pip install python-docx")
        exit(1)
    
    # 可以先运行测试看看序号检测是否正确
    # test_numbering_detection()
    # print("-" * 50)
    
    main()
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容