You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python提取字符串中「数字+bedroom」格式的指定文本?

用Python提取文本中的卧室数量信息

你可以用Python的re正则表达式模块来实现这个需求,直接匹配「数字 + bedroom(不区分大小写)」的模式,再统一输出格式即可。

代码示例

import re

# 待处理的文本列表
texts = [
    "Luxyry 2 bedroom apartment",
    "Deluxe apartment 2 bedroom",
    "Super luxyry 3 bedroom apartment",
    "1 Bedroom studio apartment"
]

# 预编译正则模式:匹配数字 + 不区分大小写的bedroom
# (\d+) 用于捕获数字部分,re.IGNORECASE 忽略大小写差异
pattern = re.compile(r'(\d+) bedroom', re.IGNORECASE)

# 遍历每个文本提取并格式化结果
for text in texts:
    match_result = pattern.search(text)
    if match_result:
        # 提取捕获的数字,拼接成统一格式的字符串
        formatted_result = f"{match_result.group(1)} bedroom"
        print(formatted_result)

代码说明

  • re.compile预编译正则表达式,提升多次匹配的效率,re.IGNORECASE确保能匹配到bedroom和Bedroom两种写法。
  • (\d+)是正则分组,用于提取数字部分,后续通过match_result.group(1)获取该数字。
  • pattern.search(text)在每个字符串中查找第一个符合模式的内容,找到后就格式化为你需要的「{卧室数量} bedroom」样式。

运行结果

2 bedroom
2 bedroom
3 bedroom
1 bedroom

内容的提问来源于stack exchange,提问作者rudra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 14:35:22