0

I have multiple .txt files that contain multiple lines similar to this:

[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825
[class2] 14:-31.8679 7:-32.3582 2:-32.4127 1:-32.7257 8:-32.9804 16:-33.2156

I want to know how to read the numbers before the :s and store them in an array.

3 Answers 3

2
>>> import re
>>> text = "[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825"
>>> map(int, re.findall(r'(\S+):\S+', text)) # You could also do map(float,...)
[1, 9, 13, 2, 17, 8, 14]
Sign up to request clarification or add additional context in comments.

Comments

1

I would use regex but here is a version without, clearer than @Thrustmaster's solution imo.

>>> text = "[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825"
>>> [int(x.split(':')[0]) for x in text.split()[1:]]
[1, 9, 13, 2, 17, 8, 14]

7 Comments

May be you could make it take multiple lines this way too: [[int(x.split(':')[0]) for x in line.split()[1:]] for line in arr]
@Thrustmaster Yeah that would work, I was just showing a small example so the OP can extend it.
@AiureaAdicatotYO No problem but regex is better!
@jamylak so for each file i should do smth like f=open('path','r') text=f.readlines() and then that split function? ?
You can just iterate over each line like: for line in open('path'): and do the operation then. Do you want all the numbers in the same array? You can see @Thrustmaster 's solution since he has already done that
|
1

Or without using RE, if you know for sure the syntax of the file remains the same, you could use this:

>>> arr
['[class1] 1:-28 9:-315 13:-354227 2:-36.247 17:-342 8:-34 14:-3825', '[class2] 14:-31.8679 7:-32.3582 2:-32.4127 1:-32.7257 8:-32.9804 16:-33.2156']
>>> newArr = [map(lambda y: int(y[:y.index(":")]),x.split(" ")[1:]) for x in arr]
>>> newArr
[[1, 9, 13, 2, 17, 8, 14], [14, 7, 2, 1, 8, 16]]

UPDATE:

If you have several files, may be you would do something like this (based on @jamylak's clearer version of my solution):

[[[int(x.split(':')[0]) for x in line.split()[1:]] for line in open(fileName)] for fileName in fileNames]

where fileNames is the array of files you are speaking about

2 Comments

@thebjorn Yes, it is. Its just another approach :)
I don't know if i asked the question right. I'll be even more specific. I have 25 .txt files each containing 354 lines. Every line looks like those i posted.

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.