【问题标题】:Find and count instance of substring within multiple strings using python使用python在多个字符串中查找和计算子字符串的实例
【发布时间】:2021-06-03 07:08:35
【问题描述】:

我在 python 中有一个带有多个子查询的 sql 查询。所以设置是一个较大字符串中的多个子字符串。我想检查子字符串中字符串的实例数。比我所看到的更多参与并感谢帮助。

这样设置 -

qry = ''' 
with 
qry_1 as ( 
   SELECT ID, 
          NAME
   FROM   ( ... other code...
),
qry_2 as ( 
    SELECT coalesce (table1.ID, table2.ID) as ID,
           NAME
   FROM (...other code...
),
qry_3 as (
     SELECT id.WEATHER AS WEATHER_MORN,
            ROW_NUMBER() OVER(PARTITION BY id.SUN
                ORDER BY id.TIME) AS SUN_TIME,
            id.RAIN,
            id.MIST
   FROM (...other code..
)
'''

我想统计IDqry_1, qry_2, qry_3 的实例。

我认为会利用 re.findall 然后进行子字符串搜索?

re.findall(r'as \( select (.+?) from \(',qry)

然后在其中查找和计数ID 的实例?输出是 2。但我不确定如何......

【问题讨论】:

    标签: python regex string substring


    【解决方案1】:

    您可以拆分 CTE 查询,然后在子查询的截断版本上使用 re.findall

    qry = ''' 
    with 
    qry_1 as ( 
      SELECT ID, 
          NAME
      FROM   ( ... other code...
    ),
    qry_2 as ( 
      SELECT coalesce (table1.ID, table2.ID) as ID,
           NAME
    FROM (...other code...
    ),
    qry_3 as (
      SELECT WEATHER
    FROM (...other code..
    )
    '''
    
    def get_cols(s):
       [cte_name] = re.findall('^\w+(?=\sas)|(?<=with\s)\w+(?=\sas)', s)
       cols = re.findall('(?<=as\s)[\w\.]+|(?<=SELECT\s)[\w\.]+|(?<=,\s)[\w\.]+', s)
       return [cte_name, cols]
    
    #dictionary with the cte name as the key, and the columns as the values
    v = dict(get_cols(re.sub('coalesce\s\(.+\)|[\s\n]+', ' ', i)) for i in re.split('(?<=\)),(?:\s+)*\n', qry))
    #filter the dictionary above to only include desired column names
    r = {a:k if (k:=[i for i in b if i in {'NAME', 'ID'}]) else None for a, b in v.items()}
    

    输出:

    {'qry_1': ['ID', 'NAME'], 'qry_2': ['ID', 'NAME'], 'qry_3': None}
    

    【讨论】:

    • 太棒了,这真的很有帮助!如果我想在计数中包括字符串是否也包含ID,例如table.ID 的实例,我可以这样做吗?
    • @paranormaldist 请看我最近的编辑
    • 这太棒了!如果可能的话,还有一个额外的问题,在输出中包含IDNAME{'qry_1': 'ID', 'NAME', 'qry_2': 'ID','NAME', 'qry_3': None}
    • @paranormaldist 请看我最近的
    • @paranormaldist 感谢您使用新的qry 字符串进行更新,请参阅我最近的编辑。
    猜你喜欢
    • 2019-04-24
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2021-08-13
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多