【发布时间】:2015-10-16 02:59:27
【问题描述】:
我有一个描述列表,我想使用正则表达式提取单位信息
我在正则表达式上观看了video,这就是我得到的
import re
x = ["Four 10-story towers - five 11-story residential towers around Lake Peterson - two 9-story hotel towers facing Devon Avenue & four levels of retail below the hotels",
"265 rental units",
"10 stories and contain 200 apartments",
"801 residential properties that include row homes, town homes, condos, single-family housing, apartments, and senior rental units",
"4-unit townhouse building (6,528 square feet of living space & 2,755 square feet of unheated garage)"]
unit=[]
for item in x:
extract = re.findall('[0-9]+.unit',item)
unit.append(extract)
print unit
这适用于以单位结尾的字符串,但我也以'rental unit','apartment','bed' 和其他字符串结尾,如本例所示。
我可以使用多个正则表达式来做到这一点,但是有没有办法在一个正则表达式中做到这一点?
谢谢!
【问题讨论】:
-
使用组:
(?:rental unit|apartment|bed)代替固定词 -
谢谢!我不知道这件事。再次感谢!
-
如果你不知道单位列表,你不能只使用正则表达式。比如说,你可以使用
r'\d+(?:\.\d+)?[\s-]\w+,但它只会抓取801 residential,而不是801 residential properties。正则表达式没那么聪明。 -
@stribizhev 感谢您的评论。你能详细说明一下吗?抱歉,我是正则表达式的新手。我不确定我理解你的意思.. 虽然我只需要单元数,但我想确保我提取的是真实单元而不是 # 故事/停车场等。再次感谢!
-
您的预期输出是什么?检查this demo。