[Tutor] Retrieving numbers from a text
Steven D'Aprano
steve at pearwood.info
Wed Oct 24 01:16:19 CEST 2012
On 24/10/12 09:45, Rufino Beniga wrote:
> My problem is, I don't know how to get ONLY the numbers from the
> OneDMap.txt file. Also, assuming that I am able to do just that, how would
> I get them into an array?
What we need to see is typical contents of your file. I expect it looks
something like this:
iterate number 562 0.4532888
iterate number 563 0.3872701
iterate number 564 0.9100345
iterate number 565 0.0027318
iterate number 566 0.6661924
and so forth.
In that case, you can read the final column by reading each line, splitting
into words, and taking only the last one. Since this is homework, I'll give
you the pieces you need to use, you should be able to assemble them into
working code yourself.
To read each line in a file:
for line in open("name of file"):
process line
Replace "process line" with the actual code you need.
To build up a list of numbers:
numbers = []
numbers.append(0.3)
numbers.append(0.9736)
numbers.append(0.3209)
Normally you would put the "numbers.append(x)" into a loop,
something like this:
numbers = []
for item in many_items:
value = process(item)
numbers.append(value)
Hint: reading a file gives you a loop, one for each line. You
want to process each line to get a number, then append that
number to the list of numbers.
You will have lines of text that look like this:
line = "iterate number 563 0.3872701"
which is a string, you need to extract the last column and
turn it into a float. Hints:
use line.split() to split the line into four words:
words = line.split()
print words
=> prints ['iterate', 'number', '563', '0.3872701']
use words[-1] to extract the last word
use function float(word) to convert it from a string to a
number.
If you put all those pieces together, it should take no more
than a dozen lines of code to read the file, and extract the
final column into a list of numbers.
Good luck!
--
Steven
More information about the Tutor
mailing list