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 标红加粗了,但后面的就不会了,如果要把第二个也加粗,那需要另寻他法

相关推荐
123的故事8 小时前
工具分享(7)-多Excel文件内容查询工具
c#·excel·实用工具
hikktn12 小时前
Excel 导出 OOM 预防实战:30 万行从堆溢出到 50MB 的演进
java·excel·easyexcel
yunceqing19 小时前
从Excel调度到TMS平台:物流软件开发避坑清单
大数据·前端·网络·人工智能·excel·推荐算法
什仙19 小时前
Mathcad Prime 对比 Excel/MATLAB/Mathematica:核心优势速览
excel
快乐的哈士奇19 小时前
【Next.js实战②】Excel 派送表动态解析:表头识别与 FIELD_ALIASES 映射
前端·javascript·excel
daols8819 小时前
vue vxe-table 复制数据到 Excel:支持带表头复制
vue.js·excel·vxe-table
海兰1 天前
【web应用】Excel 项目数据自动化分析系统(AI 驱动分析)详细设计与部署指南(附源代码)
前端·人工智能·自动化·excel
2501_930707782 天前
使用 C# 代码读取或删除 Excel 文档属性
excel
hikktn2 天前
Excel 日期格式统一治理:从“显示不全“到“自动兼容“的完整方案
windows·python·excel
霸道流氓气质2 天前
Spring Boot 大数据量 Excel 导入导出功能实现指南
spring boot·后端·excel