Parsing text file containing unique pattern using Python

0

How to parse a text file containing this pattern "KEYWORD: Out:" and dump the result into output file using Python?

input.txt

DEBUG 2020-11:11:17.401 KEYWORD: Out:0xaaaf0000 In:0x80000000.1110ffff.
DEBUG 2020-11:11:17.401 KEYWORD: Out:0xaaaf00cc In:0x80000000.1110ffaa.

output.txt

0xaaaf0000:1110ffff 
0x80000000:1110ffaa
python
python-3.x
python-2.7
asked on Stack Overflow Dec 10, 2020 by sam • edited Dec 10, 2020 by sam

3 Answers

1

You could use a regex:

import re 

txt='''\
DEBUG 2020-11:11:17.401 KEYWORD: Out:0xaaaf0000 In:0x80000000.1110ffff.
DEBUG 2020-11:11:17.401 KEYWORD: Out:0xaaaf00cc In:0x80000000.1110ffaa.'''

pat=r'KEYWORD: Out:(0x[a-f0-9]+)[ \t]+In:0x[a-f0-9]+\.([a-f0-9]+)'

>>> '\n'.join([m[0]+':'+m[1] for m in re.findall(pat, txt)])
0xaaaf0000:1110ffff
0xaaaf00cc:1110ffaa

If you want to do this line-by-line from a file:

import re

pat=r'KEYWORD: Out:(0x[a-f0-9]+)[ \t]+In:0x[a-f0-9]+\.([a-f0-9]+)'

with open(ur_file) as f:
    for line in f:
        m=re.search(pat, line) 
        if m:
            print(m.group(1)+':'+m.group(2))
answered on Stack Overflow Dec 10, 2020 by dawg • edited Dec 10, 2020 by dawg
0
In [6]: lines
Out[6]:
['DEBUG 2020-11:11:17.401 KEYWORD: Out:0xaaaf0000 In:0x80000000.1110ffff.',
 'DEBUG 2020-11:11:17.401 KEYWORD: Out:0xaaaf00cc In:0x80000000.1110ffaa.']

In [7]: [x.split('Out:')[1].split(' ')[0] + ':' + x.split('In:')[1].split('.')[1] for x in lines]
Out[7]: ['0xaaaf0000:1110ffff', '0xaaaf00cc:1110ffaa']
answered on Stack Overflow Dec 10, 2020 by idar
0

I think the 2nd line for your 'output.txt' might be wrong (or complex if not - you'd need to point this out).

Otherwise, maybe a RegEx like this:

(.*Out:)(0x[0-9a-f]{1,8}) In:0x[0-9a-f]{1,8}\.([0-9a-f]{1,8}).

https://regex101.com/r/lMrR06/2

answered on Stack Overflow Dec 10, 2020 by DennisVM-D2i

User contributions licensed under CC BY-SA 3.0