excel标记文本中的关键词加红加粗

任务:

有这么一张表,关键词为 word,文本内容为 text,现在想把 text 中的 word 标红加粗,如果数据量少,文本段手动标还可以,多起来就不太方便了

代码:

python 复制代码
import pandas as pd
import xlsxwriter

df = pd.read_excel('data.xlsx')
out_path = 'label.xlsx'
workbook = xlsxwriter.Workbook(out_path)
worksheet = workbook.add_worksheet('Sheet1')  # 创建 sheet1
bold_red = workbook.add_format({'bold': True, 'color': 'red'})  # 配置加粗,红色

header = df.columns.tolist()
worksheet.write_row(0, 0, header)  # 在 0行0列写入表头

for i, row in df.iterrows():
    word = row['word']
    text = row['text']
    for h in range(len(header)):
        if header[h] != 'text':  # 保留其他原始列的值
            worksheet.write(i + 1, h, row[header[h]])
        else:
            if word in str(text):
                word_len = len(word)
                word_index = text.find(word)
                # 关键词在开头或结尾需要特殊处理
                if text.startswith(word):
                    worksheet.write_rich_string(i + 1, h, bold_red, word, text[word_index + word_len:])
                elif text.endswith(word):
                    worksheet.write_rich_string(i + 1, h, text[:word_index], bold_red, word)
                else:
                    worksheet.write_rich_string(i + 1, h, text[:word_index], bold_red, word, text[word_index + word_len:])
            else:
                worksheet.write(i + 1, h, text)  # 不包含 word 的原文正常写入

workbook.close()

可以看到每条 text 中出现的第一个 word 标红加粗了,但后面的就不会了,如果要把第二个也加粗,那需要另寻他法

相关推荐
ken223214 小时前
excel表格为什么越存文件越大? libreoffice 有效
excel
华大哥16 小时前
spring boot 和php 调用 LibreOffice 转换 Excel 到 PDF 完整实现
java·pdf·excel
Codiggerworld1 天前
Vim 实战:在 VS Code、JetBrains、终端里玩转 Vim
编辑器·vim·excel
开开心心_Every1 天前
多连接方式的屏幕共享工具推荐
运维·服务器·pdf·电脑·excel·tornado·dash
Jun6263 天前
QT(4)-EXCEL操作
开发语言·qt·excel
2501_907136823 天前
Excel文件强效安全修复工具-清理安全风险 可修复WPS编辑后Excel无法打开的文件
excel·wps
一位代码3 天前
Excel 文本连接符 & :基础用法与进阶技巧详解
excel
焱文8193 天前
wps excel指定数据区域,二维码生成区域,批量生成单元格二维码VBA宏代码
excel·wps
夏天里的肥宅水3 天前
EXCEL生成日历
excel
我命由我123454 天前
Excel - Excel 单元格格式同时设置日期时间
运维·学习·职场和发展·excel·求职招聘·职场发展·学习方法