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

相关推荐
wuyk5552 天前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
黎羽_3 天前
Excel 插图在手机端不显示/错位:完整排查手册
excel·openpyxl·移动端·办公文档
用户298698530144 天前
React 前端实现 Excel 与 CSV 互转:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
仓库日记5 天前
Excel进销存何时该换?用3项检查判断是否需要软件
经验分享·excel·进销存·开单软件
用户0332126663675 天前
如何使用 Python 将 JSON 转换为 Excel
python·excel
2601_967980116 天前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
用户0332126663676 天前
使用 Python 轻松加密或解密 Excel 文档
python·excel
总裁余(余登武)7 天前
【python项目】:1操作EXCEl自动化开发
python·自动化·excel
ailitsoft9 天前
库存管理系统如何记录跨门店调拨后的收货差异?
excel·零售·软件需求
百事牛科技11 天前
Excel的三种密码:防看、防存、防乱改,各管各的
windows·excel