首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python在大段落的标记之间查找多个字符串

Python在大段落的标记之间查找多个字符串
EN

Stack Overflow用户
提问于 2021-05-15 10:16:32
回答 2查看 50关注 0票数 0

我正在试着用长字符串列出公司的列表。

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

此外,字符串的开头总是列出了一家公司。它大概是这样的:

代码语言:javascript
运行
复制
Companies = 'Apples Inc, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, Bananas LLC, 
Carrots Corp, xxxx.'

我一直在尝试使用regex来解决这个问题,但是我对python太缺乏经验了。

我最近的尝试是这样的:

代码语言:javascript
运行
复制
r = re.compile(r' .*? Inc | .*? LLC | .*? Corporation | .*? Corp',
flags = re.I | re.X)

r.findall(Companies)

但是我的输出总是

代码语言:javascript
运行
复制
['Apples Inc', ', xxxxxxxxxxxxxxxxxxx, Bananas LLC', ', Carrots Corp']

当我需要它的时候

代码语言:javascript
运行
复制
['Apples Inc', 'Bananas LLC', 'Carrots Corp']

我很恼火,我谦虚地请求帮助。

*编辑

我已经想出了一种方法,如果公司名称中包含逗号,就可以找到它,比如苹果公司。

在我对长字符串运行任何分析之前,我将让程序检查在Inc.之前是否存在任何逗号,然后删除它们。

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

EN

Stack Overflow用户

发布于 2021-05-15 10:39:01

在此特定情况下,您可以执行以下操作:

代码语言:javascript
运行
复制
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']

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

如果您可能有Apple, Inc. (这是典型的),您可以这样做:

代码语言:javascript
运行
复制
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.']

Demo and explanation of regex

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67542736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档