【问题标题】:python re.search蟒蛇研究
【发布时间】:2012-12-07 07:40:56
【问题描述】:
line=a name="12123" adfii 41:05:992 wp=wp2 这是速率​​:受控不是最大; time=300 系统循环: process=16.0 sharesize=6b2k 。

在等号之前和之后重新搜索行的最佳方法是什么。例如,我想留下 name=12123 time=300 process=16.0 sharesize=6b2k。然后放入字典

【问题讨论】:

    标签: python-3.x python-2.7


    【解决方案1】:

    尝试以下方法:

    #!python3
    
    import re
    
    line = 'line=a name="12123" adfii  41:05:992 wp=wp2 this is the rate: controlled not max; time=300 loops for the system: process=16.0 sharesize=6b2k'
    
    pattern = r'(\w+)=(\w+|".+?")'
    
    lst = re.findall(pattern, line)
    print(lst)
    
    d = dict(lst)
    print(d)
    print(d['process'])
    

    它会在我的屏幕上打印以下内容:

    c:\tmp\___python\njau_ndirangu\so13758903>py a.py
    [('line', 'a'), ('name', '"12123"'), ('wp', 'wp2'), ('time', '300'), ('process', '16'), ('sharesize', '6b2k')]
    {'line': 'a', 'sharesize': '6b2k', 'time': '300', 'name': '"12123"', 'process': '16', 'wp': 'wp2'}
    16
    

    当然可以直接写:

    d = dict(re.findall(r'(\w+)=(\w+|".+?")', line))
    

    .findall 返回匹配列表,其中一个匹配表示为以子组为元素的元组(模式内括号中的内容)。

    但要小心使用正则表达式。你很容易出错。

    【讨论】:

      猜你喜欢
      • 2010-10-27
      • 2010-10-21
      • 2016-05-28
      • 2014-08-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多