Reputation:
I want to convert a head file which is written in C to a class in python
Basically, the format of the head file in C (a file called header.c
is like following:
#define ATTR_A (HELLO +1L) /*FSDSDF*/
#define ATTR_B (HELLO +2L) /*FSFSSF*/
What I want to do is writing a simple script which can read the text from header.c
and then convert the format to a python calss and stored the result to a file called header.py
. After conversion, it will be:
ATTR_A = (HELLO +1L)
ATTR_B = (HELLO +2L)
I know how to read the file and how to store the converted result into header.py
, but I know how to do the conversion. Can someone please help me? Thanks!
Upvotes: 0
Views: 134
Reputation: 1809
I think the best way to do this is using re
here.
>>> import re
>>> testinput = '#define ATTR_A (HELLO +1L) /*FSDSDF*/'
>>> r = re.split(r'#define (\w*)(\s*)(\(.*\))', testinput)
>>> print '%s = %s' %(r[1], r[3])
ATTR_A = (HELLO +1L)
(\w*)
is used to extract the 'ATTR_A'
(\s*)
is used to extract the whitespaces
Inside (\(.*\))
, \(
actually matches (
and \)
mataches )
. .*
matches any character except a newline.
So, after the split
, r= ['', 'ATTR_A', ' ', '(HELLO +1L)', ' /*FSDSDF*/']
, which a list.
Upvotes: -1
Reputation: 101072
You can use the re module (regular expressions) to extract the parts you need from each line of text.
Example:
import re
input = ['#define ATTR_A (HELLO +1L) /*FSDSDF*/',
'#define ATTR_B (HELLO +2L) /*FSFSSF*/']
r = re.compile(r'#define (\w*)\s*(\(.*\))')
for line in input:
m = r.match(line)
print '%s = %s' % (m.group(1), m.group(2))
Output:
ATTR_A = (HELLO +1L)
ATTR_B = (HELLO +2L)
Upvotes: 3