Home > front end >  extract number from lanes in a text file in python
extract number from lanes in a text file in python

Time:07-13

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?

CodePudding user response:

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))

CodePudding user response:

Also i want to put all these values in a list but as numbers not as strings this code below gets a list but with strings. Is there any other way with regex to get speed as numerical values?

import re

text = 'tester.3'

new_list = []
idx = 0

with open('fcd.xml') as f:
    a = f.readlines()
    pattern = r'speed="([\d.] )"'
    
    for line in a:
        if text in line:
        x=(re.findall(pattern, line))
        new_list.insert(idx, x)
        idx  = 1
print(new_list)
  • Related