S Zapata S Zapata - 2 months ago 19
Python Question

Parsing floating number from ping output in text file

So I am writing this python program that must extract the round trip time from a text file that contains numerous pings, whats in the text file I previewed below:

64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=12.6ms
64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=2 ttl=60 time=1864ms
64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=3 ttl=60 time=107.8ms


What I want to extract from the text file is the 12.6, 1864, and the 107.8. I used regex to do this and have the following:

import re
ping = open("pingoutput.txt")
rawping = ping.read()
roundtriptimes = re.findall(r'times=(\d+.\d+)', rawping)
roundtriptimes.sort()
print (roundtriptimes)


The issue I'm having is that I believe the numbers are being read into the roundtriptimes list as strings so when I go to sort them they do not sort as I would like them to.

Any idea how to modify my regex findall command to make sure it recognizes them as numbers would help tremendously! Thanks!

Answer

I don't know of a way to do that in RegEx, but if you add the following line before the sort, it should take care of it for you:

roundtriptimes[:] = [float(x) for x in roundtriptimes]