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

相关推荐
czhc11400756636 小时前
LINUX 820 shell:shift,expect
linux·运维·excel
大霞上仙18 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
CodeCraft Studio20 小时前
在 Python 中操作 Excel 文件的高效方案 —— Aspose.Cells for Python
python·ui·excel·报表·aspose·aspose.cells
Techie峰1 天前
常见的 Bash 命令及简单脚本
chrome·bash·excel
小妖同学学AI1 天前
deepseek一键生成word和excel并一键下载
人工智能·word·excel·deepseek
芒果很香1 天前
MFC中使用EXCEL的方法之一
excel·mfc
y1y1z1 天前
EasyExcel篇
java·excel
CHENFU_JAVA1 天前
EasyExcel 合并单元格最佳实践:基于注解的自动合并与样式控制
java·excel
cxyll12341 天前
从接口自动化测试框架设计到开发(三)主流程封装、返回数据写入excel
前端·python·excel
QuZhengRong2 天前
【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
android·数据库·excel