Python 使用正则表达式提取单元号

Python 使用正则表达式提取单元号,python,regex,Python,Regex,我有一个描述列表,我想用正则表达式提取单元信息 我在regex上看了一个节目,下面是我得到的 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

我有一个描述列表,我想用正则表达式提取单元信息

我在regex上看了一个节目,下面是我得到的

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
这适用于unit中的字符串结尾,但我也使用“rental unit”、“公寓”、“bed”等字符串结尾,如本例所示。 我可以用多个正则表达式来实现这一点,但有没有办法在一个正则表达式中实现这一点


谢谢

只要你不害怕做一个非常长的正则表达式,你就可以使用以下内容:

compiled_re = re.compile(ur"(\d*)-unit|(\d*)\srental unit|(\d*)\sbed|(\d*)\sappartment")
unit = []
for item in x:
    extract = re.findall(compiled_re, item)
    unit.append(extract)
您必须使用一个新的|扩展regex模式,然后是针对每种可能的单元号引用类型的搜索模式。不幸的是,如果条目的一致性很低,这种方法基本上就无法使用


另外,我建议使用正则表达式测试工具,比如。它确实有助于确定您的正则表达式是否能满足您的需要。

使用组:?:租赁单元|公寓|床,而不是固定词谢谢!我不知道这件事。再次感谢!如果您不知道单位列表,则不能仅使用正则表达式。比如说,您可以使用r'\d+?:\。\d+?[\s-]\w+,但它只会获取801个住宅物业,而不是801个住宅物业。“正则表达式没那么聪明。@斯特里比雪夫谢谢你的评论。你能再详细一点吗?很抱歉,我不熟悉正则表达式。我不太明白你的意思。。我只需要单元的数量,但我想确保我提取的是真实的单元,而不是故事/停车场等。再次感谢!你的预期产出是多少?检查