【问题标题】:Use regex to extract unit number使用正则表达式提取单元号
【发布时间】: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

标签: python regex


【解决方案1】:

只要你不害怕制作一个长得可怕的正则表达式,你可以使用一些东西到:

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)

您必须使用新的“|”扩展正则表达式模式后跟每个可能的单元编号参考类型的搜索模式。不幸的是,如果条目的一致性非常低,这种方法将基本上无法使用。

另外,我可以建议使用像Regex101 这样的正则表达式测试器。它确实有助于确定您的正则表达式是否会按照您的意愿行事。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多