简体   繁体   English

Python:从txt文件中提取浮点数

[英]Python: extract floats from txt files

I have this txt file:我有这个txt文件:

TP 0.8329 

And i tried to extract that float after "TP" using the following code:我尝试使用以下代码在“TP”之后提取该浮点数:

def definir_operacao():
    end = 0
    oper = []
    for x in range(len(lines[0])):
        if(lines[0][x] == " "):
            end += 1
        elif(end == 1):
            oper.append(int(lines[0][x]))
    str2 = ''.join(oper)
    return str2


ci = definir_operacao()
print(ci)

But i get a empty variable as response, so i guess i'm making something wrong, can anyone help me?但是我得到一个空变量作为响应,所以我想我做错了什么,有人可以帮助我吗?

Just do this one-liner instead:只需这样做:

ci = float(lines[0].split()[1])

And now:现在:

print(ci)

Would give:会给:

0.8329

You're checking that whether you get an " " , and if so you're appending the exact same " " with oper .您正在检查是否得到" " ,如果是,则将完全相同的" "附加到oper See this segment again:再看这段:

if(lines[0][x] == " "):
        end += 1
elif(end == 1):
        oper.append(int(lines[0][x]))

That is why you're getting empty as response.这就是为什么你得到空作为回应。

just split the line on the basis of " " and take the second value from the splitting result.只需根据" "分割线并从分割结果中获取第二个值。 Don't forget to cast it to float.不要忘记将其投射到浮动。 That will give you what you want.那会给你你想要的。

res = float(lines[0].split(" ")[1])
    

You can just use split() too as @U11-Forward mentioned, because default separator is whitespace.您也可以像@U11-Forward 提到的那样使用 split() ,因为默认分隔符是空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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