How can I make regular expressions work with dictionary?
Example:
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)
My code is not working?
I would use an ENUM instead of a dictionary to do it. Below is the code:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.