我有一个文件名为ping.txt文件它的值显示ping ip n次所用的时间。 我有我的ping.txt文件包含:
time=35.9
time=32.4
我已经编写了一个python代码来单独提取这个浮点数,并使用正则表达式添加它。但我觉得下面的代码是我完成任务的间接方式。我在这里使用的findall正则表达式输出一个列表,将它们转换、连接然后添加。你知道吗
import re
add,tmp=0,0
with open("ping.txt","r+") as pingfile:
for i in pingfile.readlines():
tmp=re.findall(r'\d+\.\d+',i)
add=add+float("".join(tmp))
print("The sum of the times is :",add)
我的问题是如何解决这个问题而不使用regex或任何其他方法来减少代码中的行数以提高效率? 换句话说,我可以使用不同的正则表达式或其他方法来执行此操作吗? ~
您可以使用以下选项:
输出:
注意:我假设文件的每一行都包含
time=some_float_number
你可以这样做:
如果您有字符串:
然后要获得值,您只需要:
对于带有简单分隔符的对象,不需要正则表达式。你知道吗
相关问题 更多 >
编程相关推荐