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

如何用Pandas批量替换DataFrame描述中的术语/缩写为链接?

问题:Pandas批量替换DataFrame描述中的术语/缩写为HTML链接

现有如下DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([
        ['Mind Map', 'MM', '...'], 
        ['Other Term', '', 'Some other term with some words like communication and references to glossary and MM.'], 
        ['Another Term', '', 'Another term with a reference to other term and glossary.'],
        ['Glossary', '', '...']
        ]),columns=['Term', 'Abbreviation', 'Description'])

可以看到Other Term和Another Term的Description列中存在对DataFrame内其他术语或缩写的引用。需求是:当Description列中出现DataFrame内已定义的术语或缩写(不区分大小写)时,将其替换为指定HTML链接:<a href="search.com/?q=$Term">\1</a>,例如Other Term的描述中需替换glossary和MM,Another Term的描述中需替换other term和glossary。

当前已实现单个术语的替换代码,但仅能替换固定单个术语/缩写:

import re
pd.set_option('display.max_colwidth', None)
term = 'Glossary'
df['Description'].apply(
    lambda x: re.sub(r'\b(' + term + r')\b',
                     '&lt;a href=&quot;search.com/?q=' + term + r'&quot;&gt;\1&lt;/a&gt;', 
                     x, flags=re.IGNORECASE))

希望在不使用循环的前提下扩展为批量替换所有术语和缩写,能否用Python Pandas实现?


解决方案

可以实现,核心思路是先构建包含所有术语和缩写的正则匹配规则,同时关联每个匹配项对应的原Term,再通过一次apply完成批量替换,无需显式循环:

步骤说明

  1. 收集匹配条目:提取所有Term列的值,以及Abbreviation列的非空值,同时为每个匹配项绑定对应的原Term(因为缩写的链接参数需要指向原术语)。
  2. 排序匹配规则:将匹配条目按长度倒序排列,避免短条目先匹配覆盖长条目(比如先匹配Other Term而不是被拆成Other和Term单独匹配)。
  3. 构建正则模式:用|连接所有匹配条目,添加单词边界\b确保精确匹配,同时开启大小写不敏感模式。
  4. 定义替换逻辑:根据匹配到的内容,找到对应的原Term,生成目标HTML链接。

完整代码

import pandas as pd
import numpy as np
import re

# 初始化DataFrame
df = pd.DataFrame(np.array([
        ['Mind Map', 'MM', '...'], 
        ['Other Term', '', 'Some other term with some words like communication and references to glossary and MM.'], 
        ['Another Term', '', 'Another term with a reference to other term and glossary.'],
        ['Glossary', '', '...']
        ]),columns=['Term', 'Abbreviation', 'Description'])

pd.set_option('display.max_colwidth', None)

# 1. 收集所有需要匹配的条目:(匹配文本, 对应原Term)
match_items = []
for idx, row in df.iterrows():
    # 添加术语本身
    match_items.append((row['Term'], row['Term']))
    # 添加非空缩写
    if row['Abbreviation'].strip():
        match_items.append((row['Abbreviation'], row['Term']))

# 2. 按匹配文本长度倒序排序,避免短文本优先匹配
match_items.sort(key=lambda x: -len(x[0]))

# 3. 构建正则模式:单词边界包裹,支持大小写不敏感
pattern = re.compile(r'\b(' + '|'.join(re.escape(item[0]) for item in match_items) + r')\b', flags=re.IGNORECASE)

# 4. 定义替换函数
def replace_match(match):
    matched_text = match.group(1)
    # 找到对应的原Term(不区分大小写)
    target_term = next(item[1] for item in match_items if item[0].lower() == matched_text.lower())
    return f'<a href="search.com/?q={target_term}">{matched_text}</a>'

# 5. 应用替换到Description列
df['Description'] = df['Description'].apply(lambda x: pattern.sub(replace_match, x))

# 查看结果
print(df['Description'])

输出结果

0                                                                                                 ...
1    Some <a href="search.com/?q=Other Term">other term</a> with some words like communication and references to <a href="search.com/?q=Glossary">glossary</a> and <a href="search.com/?q=Mind Map">MM</a>.
2    Another term with a reference to <a href="search.com/?q=Other Term">other term</a> and <a href="search.com/?q=Glossary">glossary</a>.
3                                                                                                 ...
Name: Description, dtype: object

内容的提问来源于stack exchange,提问作者WG-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:15:39