【问题标题】:How to search for specific strings using Python and Regex如何使用 Python 和 Regex 搜索特定字符串
【发布时间】:2019-03-12 01:39:17
【问题描述】:

老实说,我不知道为什么这不起作用我专门试图确定哪个代码是

  • 雪 (SN)
  • 冻雨(FZDZ,FZRA)
  • 颗粒(IC,PL,IP)和
  • 混合类型,来自RAPL|PLRA|SNPL|PLSN|SNFZDZ|SNFZRA|RASN|SNRA|DZSN|SNDZ+- 或无符号。

提前致谢。

导入库

import pytaf
import re 

values = "TAF KZZZ 072336Z 0800/0900 11006KT P6SM SN OVC060 FM080100 11006KT P6SM SN OVC060 FM080200 11006KT P6SM SN OVC060"

taf = pytaf.TAF(values)

def precip_extraction_function(taf):

precip_groups=taf._raw_weather_groups


snow = re.compile(r"SN")
pellets = re.compile(r"/-PL/|/IC/")
freezing = re.compile(r"/FZRA/|/FZDZ/")
mix=re.compile(r"(RAPL|PLRA|SNPL|PLSN|SNFZDZ|SNFZRA|RASN|SNRA|DZSN|SNDZ)")
precip_tf=[]

for lines in precip_groups:
    print(lines)
        # initilzing vars
    if (bool(snow.match(lines))) and not (bool(pellets.match(lines)) or bool(freezing.match(lines))):
        precip_tf.append(100)
    elif (bool(pellets.match(lines))) and not (bool(snow.match(lines)) or bool(freezing.match(lines))):
        precip_tf.append(200)
    elif (bool(freezing.match(lines))) and not (bool(snow.match(lines)) or bool(pellets.match(lines))):
        precip_tf.append(300)
    elif (bool(mix.match(lines))) and not (bool(freezing.match(lines)) or bool(snow.match(lines)) or bool(pellets.match(lines))): 
        precip_tf.append(400)
    elif not (bool(mix.match(lines)) or bool(freezing.match(lines)) or bool(snow.match(lines)) or bool(pellets.match(lines))):
        precip_tf.append(-999)
return(precip_tf)

打印(precip_extraction_function(taf))

【问题讨论】:

    标签: python regex python-3.x string


    【解决方案1】:

    re.match 只匹配字符串的开头。要匹配字符串中的任何位置,您需要改用re.search。例如(我没有遵循您根据各种降水组合附加的数字代码,因此下面的示例仅输出每组的一种或多种降水类型以进行说明):

    from pytaf import TAF
    import re 
    
    values = "TAF KZZZ 072336Z 0800/0900 11006KT P6SM SN OVC060 FM080100 11006KT P6SM SN OVC060 FM080200 11006KT P6SM SN OVC060"
    
    precip = {
        'snow': r'SN',
        'pellets': r'-PL|IC',
        'freezing': r'FZRA|FZDZ',
        'mix': r'RAPL|PLRA|SNPL|PLSN|SNFZDZ|SNFZRA|RASN|SNRA|DZSN|SNDZ'
    }
    
    precip_tf = []
    precip_groups = TAF(values)._raw_weather_groups
    for g in precip_groups:
        precip_tf.append(' '.join([k for k, v in precip.items() if re.search(v, g)]))
    
    print(precip_tf)
    # ['snow', 'snow', 'snow']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      相关资源
      最近更新 更多