提取 python 文本中某些标记之后出现的第一个数值



我有以下形式的句子。我想提取任何给定标记之后出现的所有数值。例如,我想提取短语"tangible net worth"之后的所有数值

例句:

  1. "公司必须保持最低100000000美元的有形净资产和0.5的杠杆率">
  2. "公司需要维持的最低有形净资产为50000000美元"。

从这两个句子中,我想提取"$100000000""$50000000"并创建一个这样的字典:

{
"tangible net worth": "$100000000"
}

我不确定如何使用repython 模块来实现这一点。此外,这里需要小心,很大一部分句子包含多个数值。因此,我只想提取比赛后发生的即时值。我尝试了以下表达式,但没有一个给出预期的结果

re.search(r'net worth.*(d+)', sent)
re.search(r'(net worth)(.*)(d+)', sent)
re.search(r'(net worth)(.*)(d?)', sent)
re.findall(r'tangible net worth (.*)?(d* )', sent)
re.findall(r'tangible net worth (.*)?( d* )', sent)
re.findall(r'tangible net worth (.*)?(d)', sent)

对正则表达式的一点帮助将不胜感激。谢谢。

您可以使用此正则表达式:

tangible net worthD*(d+)

这将跳过tangible net worth后的任何非数字字符,然后再捕获其后出现的第一个数字。

然后,您可以将结果放入字典中。 注意我建议存储一个数字而不是一个字符串,因为您始终可以在输出时格式化它(添加$、逗号千位分隔符等)。

strs = [
"A company must maintain a minimum tangible net worth of $100000000 and leverage ratio of 0.5",
"Minimum required tangible net worth the firm needs to maintain is $50000000"
]
result = []
for sent in strs:
m = re.findall(r'tangible net worthD*(d+)', sent)
if m:
result += [{ 'tangible net worth' : int(m[0]) }]
print(result)

输出:

[
{'tangible net worth': 100000000},
{'tangible net worth': 50000000}
]

您可以使用:

tangible net worth.*?($?d+)

这将搜索"有形净资产",然后获取下一个数值(可选$)作为捕获组。正则表达式 101 链接。

<小时 />
import re
s = """
A company must maintain a minimum tangible net worth of $100000000 and leverage ratio of 0.5
Minimum required tangible net worth the firm needs to maintain is $50000000"""
pat = re.compile(r"tangible net worth.*?($?d+)")
out = [{"tangible net worth": v} for v in pat.findall(s)]
print(out)

指纹:

[
{"tangible net worth": "$100000000"}, 
{"tangible net worth": "$50000000"}
]

最新更新