Search code examples
pythonregextextnumbersline

extract number from lanes in a text file in python


I have a text file that each line of it is as follows:

    <vehicle id="tester.3" x="6936.49" y="10.20" angle="90.00" type="tester" speed="24.87" pos="6336.49" lane="longedge_3" slope="0.00"/>
    <vehicle id="tester.4" x="4388.72" y="7.00" angle="90.00" type="tester" speed="22.57" pos="3788.72" lane="longedge_2" slope="0.00"/>
    <vehicle id="tester.5" x="2075.13" y="13.40" angle="90.00" type="tester" speed="23.30" pos="1475.13" lane="longedge_4" slope="0.00"/>

in each line i need to extract the value of speed

the python code i use is

import re

with open('fcd.xml') as f:
  a = f.readlines()
  pattern = r'speed=([\d.]+)'

  for line in a:
    print(re.search(pattern, line)[1])

The code can't run it shows the below

TypeError: 'NoneType' object is not subscriptable

can anyone help?


Solution

  • Something like this should work:

    import re
    
    with open('fcd.xml') as f:
      a = f.read()
      pattern = r'speed="([\d.]+)"'
      print(re.findall(pattern, a))