0

I'm really new on Python so I need your help

I have a text like this:

19 , 22.3 ,22.24 , 79 , 40.764767 ,29.932207  
1 , 24.38 ,24.50 , 586 , 40.762291 ,29.919300  
11 , 23.13 ,23.24 , 105 , 40.763786 ,29.929407  
12 , 22.38 ,23.56 , 71 , 40.765610 ,29.941540  
5 , 23.2 ,24.15 , 173 , 40.763805 ,29.929356  

I tried to split:

array = file.read().split(",")

but result was like so

['19 ', ' 22.3 ', '22.24 ', ' 79 ', ' 40.764767 ', '29.932207  \n1 ',
 ' 24.38 ', '24.50 ', ' 586 ', ' 40.762291 ', '29.919300  \n11 ', ' 23.13 ',
'23.24 ', ' 105 ', ' 40.763786 ', '29.929407  \n12 ', ' 22.38 ', '23.56 ', 
' 71 ', ' 40.765610 ', '29.941540  \n5 ', ' 23.2 ', '24.15 ', ' 173 ',
 ' 40.763805 ', '29.929356 \n']

But I want to make it without '\n' because after split operation , I have to return string to int . So how can I make it ?

0

4 Answers 4

5
import re
x="""19 , 22.3 ,22.24 , 79 , 40.764767 ,29.932207
1 , 24.38 ,24.50 , 586 , 40.762291 ,29.919300
11 , 23.13 ,23.24 , 105 , 40.763786 ,29.929407
12 , 22.38 ,23.56 , 71 , 40.765610 ,29.941540
5 , 23.2 ,24.15 , 173 , 40.763805 ,29.929356  """
print re.split(r" *, *|\n", x)

You can do it in one go using re.

Output:['19', '22.3', '22.24', '79', '40.764767', '29.932207', '1', '24.38', '24.50', '586', '40.762291', '29.919300', '11', '23.13', '23.24', '105', '40.763786', '29.929407', '12', '22.38', '23.56', '71', '40.765610', '29.941540', '5', '23.2', '24.15', '173', '40.763805', '29.929356 ']

Sign up to request clarification or add additional context in comments.

Comments

0

Does this work:

array = [file.read().replace('\n','').split(',')]

Comments

-1

This should work:

array = [line.split(',') for line in file.read().splitlines()

Comments

-1

Your text file has six floats per line.

If you want each line kept separate:

with open("path/to/file", "rt") as f:
    data = [ [float(v.strip()) for v in l.strip().split(',')] 
            for l in f]

If you just want an array containing all the numbers (i.e. ignoring line structure of file)

with open("path/to/file", "rt") as f:
    data = [ float(v.strip()) 
             for l in f 
             for v in l.strip().split(',')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.