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

使用Python正则表达式去除常见公司名称后缀

公司名称后缀去除问题修复

问题场景

需要清理公司名称中的各类后缀,但当前代码未达到预期效果:

预期处理结果

原始名称:

Apple Inc.
Sony Corporation
Fiat Chrysler Automobiles S.p.A.
Samsung Electronics Co., Ltd.

清理后名称:

Apple
Sony
Fiat Chrysler Automobiles
Samsung Electronics

当前实现代码

import re

def remove_company_suffixes(company_name):
  suffix_pattern = r"\s*(?:co(?:rp(?:oration)?|mpany)?|ltd\.|llc|gmbh|sa|sp\.a\.|s\.r\.l\.|ag|nv|bv|inc\.|s\.a\.s\.|e\.u\.|s\.l\.|s\.a\.l\.|doo|dooel|d.o.o.|szr|ltd|inc|llc|corp|ag|sa|sp|sl)\.?$"
  return re.sub(suffix_pattern, '', company_name.strip())

company_names = ["Apple Inc.", "Sony Corporation", "Fiat Chrysler Automobiles S.p.A.", "Samsung Electronics Co., Ltd.", "Plasticos SA", "ABC GmbH"]
for company_name in company_names:
  cleaned_name = remove_company_suffixes(company_name)
  print(cleaned_name)

实际运行结果

Apple
Sony
Fiat Chrysler Automobiles S.p.A.
Samsung Electronics Co.,
Plasticos
ABC

问题分析

现有正则存在两个核心缺陷:

  1. 大小写匹配限制:正则里的sp\.a\.是小写规则,但目标文本是大写S.p.A.,默认区分大小写导致匹配失败;
  2. 组合后缀未覆盖:Co., Ltd.是带逗号的组合后缀,现有正则仅支持独立后缀匹配,无法处理这类带标点分隔的场景。

修复方案

调整正则表达式,解决上述问题:

  • 添加(?i)开启不区分大小写模式,兼容大小写后缀;
  • 新增带逗号的组合后缀匹配规则;
  • 优化后缀的点符号匹配逻辑,兼容有无点的写法。

修正后的代码

import re

def remove_company_suffixes(company_name):
    # 开启不区分大小写,覆盖组合后缀与独立后缀
    suffix_pattern = r"(?i)\s*(?:co\.?,\s*ltd\.?|co(?:rp(?:oration)?|mpany)?|ltd\.?|llc|gmbh|sa\.?|sp\.?a\.?|s\.?r\.?l\.?|ag|nv|bv|inc\.?|s\.?a\.?s\.?|e\.?u\.?|s\.?l\.?|s\.?a\.?l\.?|doo|dooel|d\.?o\.?o\.?|szr)\.?$"
    cleaned = re.sub(suffix_pattern, '', company_name.strip())
    # 清理可能残留的末尾逗号
    return re.sub(r",$", "", cleaned).strip()

company_names = ["Apple Inc.", "Sony Corporation", "Fiat Chrysler Automobiles S.p.A.", "Samsung Electronics Co., Ltd.", "Plasticos SA", "ABC GmbH"]
for company_name in company_names:
    cleaned_name = remove_company_suffixes(company_name)
    print(cleaned_name)

运行结果

Apple
Sony
Fiat Chrysler Automobiles
Samsung Electronics
Plasticos
ABC

关键优化说明

  1. (?i)修饰符:让正则忽略大小写,不管后缀是大写(S.p.A.)还是小写(sp.a.)都能匹配;
  2. co\.?,\s*ltd\.?:专门匹配Co., Ltd.这类带逗号的组合后缀,\s*兼容空格变化;
  3. 后缀点处理:用\.?表示后缀里的点可选,比如SA和SA.都能匹配;
  4. 末尾逗号清理:额外处理可能残留的逗号,确保最终结果格式干净。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:02:48