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

问题描述 投票:0回答:1

我正在努力删除一些公司名称中的后缀。预期结果如下:

原名:

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
python regex string
1个回答
0
投票

看起来您得到的结果区分大小写,因此请确保将

flags = re.IGNORECASE
传递到
re.sub
方法中,并且您的模式中的 S.p.A 也有一个拼写错误,您错过了第一个句点(您有 sp.a 而不是 s.p.a)。只剩下三星有两个公司后缀的问题了。我不知道如何处理这个问题,也许只是多次通过过滤器运行它并考虑尾随逗号。

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.