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

如何使用正则提取多行SQL字段别名后存入pandas dataframe

实现方案

1. 依赖库导入

首先导入正则处理库re和pandas:

import re
import pandas as pd

2. 别名提取逻辑

用正则匹配每一行as关键字后被单引号包裹的别名内容,该方法对大文本量处理效率较高,适配你的业务场景:

# 实际使用时替换为你的真实多行SQL文本即可
sql_text = """
max(if(serving_id in (25315,25357), option_text, null)) as 'Scheduling',
max(if(serving_id in (25316,25358), option_text, null)) as 'Check-in',
max(if(serving_id in (25317,25359), option_text, null)) as 'Services',
max(if(serving_id in (25318,25360), option_text, null)) as 'Quality of Service',
max(if(serving_id in (25319,25361), option_text, null)) as 'Returns'
"""

# 正则匹配提取所有别名
aliases = re.findall(r"as\s*'([^']+)'", sql_text)

3. 存入pandas DataFrame

直接将提取到的别名列表转为DataFrame:

df = pd.DataFrame(aliases, columns=['sql_alias'])

如果实际场景中SQL别名用双引号包裹,将正则规则改为r'as\s*"([^"]+)"'即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:57:03