Reputation: 1090
I got many data wrote in this form(read from file):
(31265+0j)
(-5613.54281374+404.957401125j)
(1371.65134844+2671.06617046j)
...
And yet I want to extract the numerical part, like [31265, 0]
or [-5613.54281374 , 404.957401125]
, I coded in python in the way I thought it would work:
re.findall(r'.*([\+|\-]?\d+.?\d+)([\+|\-]?\d+.?\d+).*', tempStr)
But it does not work, it gave me this:
[]
[('26', '5+0')]
[('11', '25')]
...
What's wrong with it? Is it something about lazy mode? And how should I fix it?
========================Update======================== For me, this question is solved, but I still wonder what's wrong with the regular expression part, is there someone willing to help me point out what's wrong with the regex pattern?
Upvotes: 2
Views: 177
Reputation: 53774
These are numbers. You should not use regex here. The first part is the real
and the second part is the imaginary
you can access them like this
n = (-5613.54281374+404.957401125j)
n.real
n.imag
This maybe hard to spot at first because in maths we often use i = sqrt(-1)
but in python it's j = sqrt(-1)
But quit interestingly, if you do
import math
math.sqrt(-1)
you will get a ValueError
Update:
If the data is in a file
with open('complex.txt') as f:
for line in f:
number = complex(line.strip())
Update 2: if you really, really, really want to use regex:
map(float, line[1:-2].split('+'))
Use re.split() instead if you have numbers where the complex part can be negative.
Upvotes: 6
Reputation: 86
Using .real and .imag will give you the output you desire
foo = (31265 + 0j)
bar = [foo.real , bar.imag]
#>>>[31265.0 , 0.0]
Upvotes: 1