【问题标题】:How to match and create a dictionary before and after the match如何在匹配前后匹配和创建字典
【发布时间】:2019-10-17 07:57:01
【问题描述】:
import re
s = 'A boy is 31 and girl is 22.'
print(re.findall(r'\S+(?=\s+is\b)', s))

out > ['男孩','女孩']

print (re.findall(r'\S+(?=\s+)is(?:\s*\S+|$)',s))

输出 > []

如果我以['boy',31,'girl',22] 的身份退出,那我可以 b = dict(zip(list_[::2], list_[1::2]))

Expected Out > {'boy':31, 'girl':22}

【问题讨论】:

    标签: python regex dictionary


    【解决方案1】:

    你可以使用

    import re
    s = 'A boy is 31 and girl is 22.'
    print(dict([(x,int(y)) for x, y in re.findall(r'(\S+)\s+is\s+(\d+)', s)]))
    ## Or, with dictionary comprehension
    print( {x:int(y) for x, y in re.findall(r'(\S+)\s+is\s+(\d+)', s)} )
    

    Python demo

    这里,模式匹配

    • (\S+) - 1+ 个非空白字符(第 1 组,x
    • \s+is\s+ - is 包含 1+ 个空格
    • (\d+) - 1+ 位(第 2 组,y

    请参阅regex demo

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2020-08-26
      • 2021-06-16
      • 1970-01-01
      相关资源
      最近更新 更多