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

相关推荐
tedcloud1231 小时前
DeepSeek-TUI部署教程:打造CLI AI助手环境
服务器·人工智能·word·excel·dreamweaver
Metaphor69211 小时前
使用 Python 在 Excel 中查找并高亮显示
python·信息可视化·excel
2501_9307077813 小时前
使用C#代码隐藏或显示 Excel 中的批注
excel
霸道流氓气质13 小时前
Excel 数据导出实战指南
excel·状态模式
雨季mo浅忆14 小时前
记录利用Cursor快速实现Excel共享编辑
前端·excel
神奇的代码在哪里16 小时前
【单机离线版】excel转json软件,纯HTML+JS零依赖实现Excel转JSON工具,一个index.html搞定所有转换!
html·json·excel·excel转json·xlsx转json·xls转json
DS随心转APP2 天前
AI 一键导出 Word 与 Excel 实战应用指南
人工智能·ai·word·excel·deepseek·ai导出鸭
spencer_tseng3 天前
excel 2003 [Cell division function]
excel·office
开开心心就好3 天前
小白友好的程序联网封锁实用工具
windows·eureka·计算机外设·rabbitmq·word·excel·csdn开发云
SunnyDays10113 天前
Python操作Excel批注:从基础添加到高级自定义的完整指南
开发语言·python·excel