简体   繁体   中英

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM