0

我正在尝试从长字符串中列出公司列表。

公司名称往往在字符串中随机分布,但在名称 ', ' 之前总是有一个逗号和一个空格,并且它们总是以 Inc、LLC、Corporation 或 Corp 结尾。

此外,总是有一家公司列在字符串的开头。它类似于:

Companies = 'Apples Inc, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, Bananas LLC, 
Carrots Corp, xxxx.'

我一直在尝试使用正则表达式来破解这个问题,但是我对 python 太缺乏经验了。

我最接近的尝试是这样的:

r = re.compile(r' .*? Inc | .*? LLC | .*? Corporation | .*? Corp',
flags = re.I | re.X)

r.findall(Companies)

但我的输出总是一些变化

['Apples Inc', ', xxxxxxxxxxxxxxxxxxx, Bananas LLC', ', Carrots Corp']

当我需要它时

['Apples Inc', 'Bananas LLC', 'Carrots Corp']

我很烦恼,我谦卑地寻求帮助。

****编辑

如果公司名称包含逗号,我已经找到了一种方法来查找公司名称,例如 Apples, Inc.

在对长字符串进行任何分析之前,我将让程序查看 Inc. 之前的 2 个空格是否存在任何逗号,然后将其删除。

然后我将运行程序列出公司名称。

4

2 回答 2

0

我认为这是何时不使用 regex的完美示例。您的结果可以通过仅基于逗号拆分字符串并检查您指定的后缀是否存在于任何分割段中来实现。

例如:

paragraph = 'Apples Inc, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, Bananas LLC, Carrots Corp, xxxx.'

suffixes = ["Inc", "Corp", "Corporation", "LLC"]

companies = []
#Split paragraph by commas
for term in paragraph.split(", "):
    #Go through the suffixes and see if any of them match with the split field
    for suffix in suffixes:
        if suffix in term:
            companies.append(term)

print(companies)

这段代码可读性更强,可能比正则表达式更容易理解。

于 2021-05-15T02:25:53.180 回答
0

在这种特殊情况下,您可以执行以下操作:

targets=('Inc', 'LLC', 'Corp', 'Corporation')

>>> [x for x in Companies.split(', ') if any(x.endswith(y) for y in targets)]
['Apples Inc', 'Bananas LLC', 'Carrots Corp']

,但是,如果名称中或名称与实体类型之间存在 a,则此方法不起作用。

如果您可能有Apple, Inc.(这将是典型的),您可以执行以下操作:

Companies = 'Apples, Inc., xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, Bananas, LLC, Carrots Corp., xxxx.'


targets=('Inc', 'LLC', 'Corp', 'Corporation')

>>> re.findall(rf'([^,]+?(?:, )?(?:{"|".join(targets)})\.?)', Companies)
['Apples, Inc.', ' Bananas, LLC', ' Carrots Corp.']

正则表达式的演示和解释

于 2021-05-15T02:39:00.760 回答