繁体   English   中英

正则表达式表达式字符串字典python

[英]regex expression string dictionary python

如何使正则表达式与字典配合使用?

例:

my_log:
Received block blk_-967145856473901804 of size 67108864 from /10.250.6.191
Received block blk_8408125361497769001 of size 67108864 from /10.251.70.211

My dictionary:
key_log = {"Received block (.*) of size ([-]?[0-9]+) from (.*)": 1}

My code:
for line in my_log:
        key_id = key_log[my_log]
        print (key_id)

我的代码不起作用?

我会用ENUM而不是字典来做到这一点。 下面是代码:

import re
import csv
from enum import Enum

#regex model
class Regex(Enum):
    ONE = "Received block (.*) of size ([-]?[0-9]+) from (.*)"
    TWO = "some other regex"

    @classmethod
    def match_value(cls, value):
        for item in cls:
            if re.match(pattern=item.value, string=value):
                return item

def main():
    with open(file='source.log', mode='r', encoding='utf-8') as f:
        for line in f.readlines():
            _match = Regex.match_value(value=line)
            if _match is not None:
                if _match.name == 'ONE':
                    with open(file='target.csv', mode='a') as csv_file:
                        csv_writer = csv.writer(csv_file)
                        csv_writer.writerow([1])
                if _match.name == 'TWO':
                    with open(file='target.csv', mode='a') as csv_file:
                        csv_writer = csv.writer(csv_file)
                        csv_writer.writerow([2])


if __name__ == '__main__':
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM