如何使用python上的简单操作从字符串中提取浮点数并将其相加

2024-10-02 00:41:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件名为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或任何其他方法来减少代码中的行数以提高效率? 换句话说,我可以使用不同的正则表达式或其他方法来执行此操作吗? ~


Tags: 文件方法代码ipretxtaddtime
3条回答

您可以使用以下选项:

with open('ping.txt', 'r') as f:
    s = sum(float(line.split('=')[1]) for line in f)

输出:

>>> with open('ping.txt', 'r') as f:
...     s = sum(float(line.split('=')[1]) for line in f)
...
>>> s
68.3

注意:我假设文件的每一行都包含time=some_float_number

你可以这样做:

import re
total = sum(float(s) for s in re.findall(r'\d+(\.\d+)?', open("ping.txt","r+").read()))

如果您有字符串:

>>> s='time=35.9'

然后要获得值,您只需要:

>>> float(s.split('=')[1]))
35.9

对于带有简单分隔符的对象,不需要正则表达式。你知道吗

相关问题 更多 >

    热门问题