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

相关推荐
Metaphor6921 小时前
如何快速拆分超大 Excel 文件【Python 教程】
python·excel
工具派4 小时前
PDF里没有表格,PDF转Excel行列是靠什么对上的?
pdf·excel
泡海椒5 小时前
JQuickExcel 大文件排障与调优:从实际路径定位 OOM、临时盘和慢任务
开发语言·数据库·缓存·oracle·excel
Data-Miner7 小时前
用 Excel 做「高级」数据统计分析的实操指南
excel
2501_930707787 小时前
使用C#代码设置 Excel 单元格的数字格式
excel
我的愿望是成为富婆11 小时前
2027校招:大数据管理与应用专业,如何用数据能力匹配电商运营与供应链管培生
人工智能·sql·excel
qyyyyy57012 小时前
WhatsApp 联系人表格怎么清洗?Excel 文本类型、重复号码与姓名冲突处理
数据库·自然语言处理·excel·hash
用户0332126663671 天前
如何快速拆分超大 Excel 文件【Python 教程】
python·excel
葡萄城技术团队1 天前
在线 Excel 怎么验收:从「能打开」到「能上线」
excel
言乐61 天前
HTML实现Word、Excel、PPT三种可切换背景,可键盘打字、和像素小人交互
html·word·powerpoint·excel·交互