Problem
Read a file and capture two tokens for every multi-line entry.
First token is hexcode with which the entry starts.
Second token is the remaining line(multi-line) of the entry. Trailing backslash indicates the continuation of line.
Typical entries of a file is as shown below:
0x0512ff01 R 5330 R XY.Zion, \
"parseexp( {f 7},{S \"OWAUTO\"})", "0x0222ff02 -:-", \
"parseexp( {g 7},{S \"TWFAB\"})", "0x0222ff02 -:-", \
"setfault", "0x0222ff03 -:-"
# whatever
0x0436ff02 I 5330 R XY.Yion, " \
! ( strcat( {H 19.19.121.180}, {attr 0x11137f }) \
"default", "0x0222ff03 -:-"
0x0236ff03 G 50
0x0588ff03 H 49
0x0777ff03 R 34
There are such ~100 files to read
Solution
Input to this function is a generator that provides path
, one at a time
def get_tokens(file_paths):
for path in file_paths:
ruleCapture = False
with open(path) as f:
for line in f:
line=line.strip() # remove \n and other spaces
if line.startswith('#'): # comments
continue
elif (not line.endswith('\\')) and (ruleCapture == False):
event_rule_match = re.search(r'(?<!\\\n)^(0[xX][0-9a-fA-F]+)([^\n]*)',line)
if event_rule_match:
yield event_rule_match.group(1), event_rule_match.group(2)
elif line.endswith('\\') and ruleCapture == False:
buffer = line[0:-2]
ruleCapture = True
elif line.endswith('\\') and ruleCapture == True:
buffer = ' '.join([buffer, line[0:-2]])
elif (not line.endswith('\\')) and ruleCapture == True:
buffer = ' '.join([buffer, line])
ruleCapture = False
event_rule_match = re.search(r'(?<!\\\n)^(0[xX][0-9a-fA-F]+)([^\n]*)',buffer)
yield event_rule_match.group(1), event_rule_match.group(2)
buffer=''
1) Can this code avoid regex?
2) Can elif
structure still be optimized?
3) Can this code avoid reading the file line by line? Instead use f.read()
and compile regex once....
(?<!\\\n)(?<=[\s]*)^(0[xX][0-9a-fA-F]+)([^\n]*)
does not work \$\endgroup\$