You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python提取多行指定文本并高亮特定内容的技术实现咨询

解决文本中特定单词的大小写不敏感高亮问题

你的现有代码只能匹配完全小写的目标单词,无法处理大小写混合的变体(比如示例里的nIcE、Nice),要实现对所有大小写形式的目标单词高亮,推荐使用正则表达式的re.sub方法,结合忽略大小写的标志来处理:

import re

def highlight_word(sentence, word):
    # 对目标单词转义避免正则语法冲突,匹配所有大小写变体并替换为大写
    return re.sub(re.escape(word), word.upper(), sentence, flags=re.IGNORECASE)

# 示例使用
original_text = "Have a nIcE day, you Nice person!!" 
highlighted_text = highlight_word(original_text, "nice") 
print(highlighted_text)

代码说明

  • re.escape(word):转义目标单词中的特殊字符,防止正则表达式解析出错
  • flags=re.IGNORECASE:开启大小写不敏感匹配,可覆盖nice、Nice、NICE、nIcE等所有大小写组合
  • 替换后所有匹配到的目标单词统一转为大写,实现高亮效果

如果你的提取结果是3-4行的多行文本,直接将文本传入函数即可自动处理所有行:

# 模拟提取出的多行文本
extracted_text = """Hello nice world
This is a Nice example
Another nIcE line here
Last line with NICE"""

highlighted = highlight_word(extracted_text, "nice")
print(highlighted)

输出结果:

Hello NICE world
This is a NICE example
Another NICE line here
Last line with NICE

内容的提问来源于stack exchange,提问作者Sachin Nayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:54:57