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

相关推荐
funnycoffee12311 小时前
EXCEL VBA Color 将选中区域 的指定字符,设置字体颜色(比如红)
excel·excel vba·vba字体颜色
m5655bj12 小时前
通过 Python 删除 Excel 中的空白行列
python·ui·excel
2501_9449347312 小时前
大专信息统计与分析专业,怎么提升Excel高级函数的使用能力?
大数据·excel
优选资源分享12 小时前
ASAP Utilities V9.2:Excel 办公效率插件 中文版
excel
技小宝12 小时前
如何在WPS/Excel中批量翻译长文本?
经验分享·职场和发展·excel·wps
AI_56781 天前
Excel数据透视表提速:Power Query预处理百万数据
数据库·excel
颜挺锐1 天前
EXCEL中A列连接B列中间加| 怎么写公式
excel
J_liaty1 天前
基于POI实现Excel文件导入导出
excel·poi
Texous2 天前
Java解析Excel图片
java·excel·wps·office·excel图片处理·excel图片解析·excel图片提取
chatexcel2 天前
从Excel到PPT:如何利用自动化工具重构数据汇报流程
自动化·powerpoint·excel