1

以下是我从网上提取的一行:

AIG $30 AIG 是一家在纽约证券交易所上市的国际知名保险公司。需要一个句号。手动自动激活 3 0.0510、0.0500、0.0300 [提取]

我想通过解析文本和检索相关数据来创建 5 个单独的变量。但是,我真的不明白 REGEX 文档!谁能指导我如何用这个例子正确地做到这一点?

名称 = AIG

当前价格 = 30 美元

状态 = 活动

World_Ranking = 3

历史 = 0.0510、0.0500、0.0300

4

1 回答 1

1

不知道你想在这里实现什么。无需使用正则表达式,您可以使用str.split

>>> str = "AIG $30 AIG is an international renowned insurance company listed on the NYSE. A period is required. Manual Auto Active 3 0.0510, 0.0500, 0.0300 [EXTRACT]"
>>> list = str.split()
>>> dict = { "Name": list[0], "CurrentPrice": list[1], "Status": list[19], "WorldRanking": list[20], "History": ' '.join((list[21], list[22], list[23])) }

#output
>>> dict
{'Status': 'Active', 'CurrentPrice': '$30', 'Name': 'AIG', 'WorldRanking': '3', 'History': '0.0510, 0.0500, 0.0300'}

而不是使用list[19]等,您可能希望将其更改list[-n]为不依赖于公司的描述长度。像那样:

>>> history = ' '.join(list[-4:-1])
>>> history
'0.0510, 0.0500, 0.0300'

对于浮动历史索引,它可能更容易使用re

>>> import re
>>> history = re.findall("\d\.\d{4}", str)
>>> ['0.0510', '0.0500', '0.0300']

为了识别状态,您可以获取历史值的索引,然后减一:

>>> [ i for i, substr in enumerate(list) if re.match("\d\.\d{4}", substr) ]
[21, 22, 23]

>>> list[21:24]
['0.0510,', '0.0500,', '0.0300,']

>>> status = list[20]
>>> status
'3'
于 2012-12-22T04:05:15.073 回答