我有一个文本文件,每一行如下:
<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"/>
中的每一行,我需要提取speed
的值我使用的python代码是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])
代码不能运行它显示如下
TypeError: 'NoneType' object is not subscriptable
有人能帮忙吗?
应该这样做:
import re
with open('fcd.xml') as f:
a = f.read()
pattern = r'speed="([d.]+)"'
print(re.findall(pattern, a))
我还想把所有这些值在一个列表中,但作为数字而不是字符串下面的代码获取一个带有字符串的列表。是否有其他的方法与正则表达式获得速度作为数值?
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)