Parsing floating number from ping output in text file
<p>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:</p>

<pre><code> 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
</code></pre>

<p>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:</p>

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

<p>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. </p>

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

<h1>Non-regex:</h1>

<p>Simply performing splits on space, grabbing the last entry, then split on <code>=</code>, grab the second part of the list and omit the last two components (ms). Cast to a float. </p>

<p>All of that is done in a list-comprehension:</p>

<p>Note that <code>readlines</code> is used to have a list containing each line of the file, which will be much easier to manage.</p>

<pre><code>with open('ping_results.txt') as f:
    data = f.readlines()

times = [float(line.split()[-1].split('=')[1][:-2]) for line in data]
print(times) # [12.6, 1864.0, 107.8]
</code></pre>

<h1>regex:</h1>

<p>The key thing here is to pay attention to the regex being used: </p>

<pre><code>time=(\d*\.?\d+)
</code></pre>

<p>Look for <code>time=</code>, then start a capture group <code>()</code>, and grab digits (<code>\d*</code>), optional decimal (<code>\.?</code>), digits (<code>\d+</code>).</p>

<pre><code>import re

with open('ping_results.txt') as f:
    data = f.readlines()

times = [float(re.findall('time=(\d*\.?\d+)', line)[0]) for line in data]
print(times) # [12.6, 1864.0, 107.8]
</code></pre>

python regex ping text-parsing