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

相关推荐
杜子腾dd11 小时前
14.使用各种读写包操作 Excel 文件:辅助模块
python·数据挖掘·excel·numpy·pandas·matplotlib
Macdo_cn12 小时前
Microsoft Excel 2024 LTSC mac v16.95 表格处理软件 支持M、Intel芯片
microsoft·macos·excel
进击的铁甲小宝12 小时前
使用 VLOOKUP 和条件格式在 Excel 中查找并标红匹配的串号
excel
石油人单挑所有16 小时前
Vim软件使用技巧
vim·excel
inxunoffice18 小时前
批量压缩与优化 Excel 文档,减少 Excel 文档大小
前端·excel
inxunoffice1 天前
批量将 Excel 文档中的图片提取到文件夹
excel
inxunoffice1 天前
批量在多个在 Excel 工作表的的指定位置插入新的 Sheet 工作表
excel
杜子腾dd1 天前
13. Pandas :使用 to_excel 方法写入 Excel文件
大数据·python·数据挖掘·excel·numpy·pandas
inxunoffice1 天前
批量删除或替换 Excel 的 Sheet 工作表
excel
人……杰1 天前
Excel两列和依次相减
excel