Python 在没有找到解决方案的情况下研究了RE模块

Python 在没有找到解决方案的情况下研究了RE模块,python,Python,使用Python2.7.5和以下字符串。我试图用下面的代码求和。有人能把我引向正确的方向吗?谢谢 <msg><src>CC128-v0.15</src><dsb>01068</dsb><time>09:19:01</time><tmprF>68.9</tmprF><sensor>0</sensor><id>00077</id><type

使用Python2.7.5和以下字符串。我试图用下面的代码求和。有人能把我引向正确的方向吗?谢谢

<msg><src>CC128-v0.15</src><dsb>01068</dsb><time>09:19:01</time><tmprF>68.9</tmprF><sensor>0</sensor><id>00077</id><type>1</type><ch1><watts>00226</watts></ch1><ch2><watts>00189</watts></ch2></msg>

try:
    watts_ex = re.compile('<watts>([0-9]+)</watts>')
    temp_ex = re.compile('<tmprF>([\ ]?[0-9\.]+)</tmprF>') 
    time_ex = re.compile('<time>([0-9\.\:]+)</time>')

    watts = str(int(watts_ex.findall(data)[0]))
    temp = temp_ex.findall(data)[0].strip() 
    time = time_ex.findall(data)[0]
except:
    sys.stderr.write("Could not get details from device")
    sys.exit()

# Replace format string
format = format.replace("{{watts}}", watts)
format = format.replace("{{time}}", time)
format = format.replace("{{temp}}", temp)

print format

if __name__ == "__main__":
    main()

""" output is 09:19:01:, 226 watts, 68.9F (watts should = 415 watts """
CC128-v0.150106809:19:0168.90000710022600189
尝试:
瓦茨编译(“([0-9]+)”)
临时编译(“([\]?[0-9\.]+)”
time\u ex=re.compile(“([0-9\.\:]+)”
瓦特=str(整数(瓦特(数据)[0]))
temp=temp_ex.findall(数据)[0].strip()
时间=时间(数据)[0]
除:
sys.stderr.write(“无法从设备获取详细信息”)
sys.exit()
#替换格式字符串
format=format.replace(“{{watts}}”,瓦特)
format=format.replace(“{time}}”,time)
format=format.replace(“{{temp}}”,temp)
打印格式
如果名称=“\uuuuu main\uuuuuuuu”:
main()
“”“输出为09:19:01:,226瓦,68.9华氏度(瓦应=415瓦”“”

这看起来像是一种类似XML的语言,我强烈建议使用XML库而不是正则表达式来解析它

代码中的问题是这一部分:

watts = str(int(watts_ex.findall(data)[0]))
您只是在使用
findall()
中的result
0
,我想您需要这样的结果:

watts = str(sum(int(w) for w in watts_ex.findall(data)))

是否要同时添加
值?目前,您只获得第一个值。是的,这就是我正在尝试的。ThanksWolph,您的新行生成以下错误:文件“/current-cost3.py”,第96行temp=temp_ex.findall(data)[0]。strip()^SyntaxError:无效语法在我的代码中做了一些其他更改后,您的答案仍然有效。