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

相关推荐
小白学大数据11 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
SunnyDays101118 小时前
如何使用 Python 添加和编辑 Excel VBA 宏(无需安装 Excel)
开发语言·python·excel·vba
GHL28427109018 小时前
codex操作excel学习
学习·ai·word·excel
一晌小贪欢3 天前
python-第15天:Python 列表推导式
开发语言·python·excel·数据可视化·python办公
tryxr3 天前
Chat2Excel 项目通用服务开发
java·开发语言·excel·java项目开发
Jazz_z3 天前
使用 Python 合并与取消合并 Excel 单元格
开发语言·python·excel
2601_962381864 天前
Python办公联动:Excel数据一键自动生成PPT图表
python·数据分析·自动化·excel·ppt
tryCbest6 天前
Excel常用公式(WPS vs Office)
excel·wps
taller_20006 天前
【006】何时用 Python?何时用 Excel 公式?一文讲清
python·excel·公式·pie·py
2601_949950636 天前
Word、PDF、Excel题目怎么快速整理?
pdf·word·excel