簡體   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