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

相关推荐
Smilecoc8 分钟前
Excel之Subtotal:功能强大的统计函数
excel
用户0332126663672 小时前
使用 Python 在 Excel 中添加或删除批注
python·excel
观远数据1 天前
Excel继续用、自研BI、替换BI:产品VP拆解三条路线的隐性成本与能力边界
大数据·人工智能·excel
用户298698530142 天前
Excel 转 PDF 免费在线工具,格式完美保留
人工智能·c#·excel
开开心心就好2 天前
文件查重软件批量删除重复文件释放空间
java·开发语言·随机森林·ocr·excel·音视频·最小二乘法
开开心心就好2 天前
文件批量重命名工具简单好用支持规则改名
java·开发语言·b树·ocr·excel·音视频·kmeans
破z晓3 天前
javascript 导出excel表
开发语言·javascript·excel
Am-Chestnuts3 天前
豆包多轮回答中的表格导出 Excel:编号、日期与长数字检查
excel
hPw0eKIqD4 天前
使用二次封装的Excel COM 组件操作Excel\WPS ET中的区域、行和列
excel·wps
冰心孤城4 天前
Excel: xls与xlsx格式转换排坑指南
java·前端·excel