![](/img/trans.png)
[英]How to extract the first and last value from a txt file, in python?
[英]how to extract value from txt file
我有数据很好data.txt:
# data1 data2 data3 W = 10.251 kg
-5.827 0.0000E+00 0.0000E+00
-5.817 0.6202E-03 0.2067E-05
-5.807 0.2481E-02 0.1654E-04
-5.797 0.5582E-02 0.5582E-04
-5.787 0.9924E-02 0.1323E-03
如何使 python 提取 W 的值作为weight = 10.251
我用这个
W_txt = np.loadtxt('./data.txt',max_rows =1, dtype=np.str, comments = 'c')
weight_txt = W_txt[8]
weight = weight_txt.astype(np.float)
print(weight)
但它带有警告:
DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
你知道如何读取 python 中的文件吗? 如果没有,您可以在网上找到大量教程。 您的文件似乎排列在由制表符分隔的列中。 此外,在最后一列中,您似乎拥有想要的价值。 您可以使用"some\ttab-delimited\tstring".split("\t")
拆分制表符分隔的 spring 以获取包含结果片段的列表。
目前尚不清楚您的文件的结构。 从外观上看,它可能是your_string = "data1\tdata2\tdata3\tW =\t10.251 kg"
。 如果您设法从文件中解析数据,并且希望从第一行中提取10.251
并将其重新格式化为 output weight = 10.251
,则代码将如下所示:
with open("/path/to/your/file.txt", "r") as f:
data = f.readlines()
# get first line
first_line = data[0]
# split string by tab, select last fragment, split again by ' kg' and select first fragment
desired_value = first_line.split("\t")[-1].split(" kg")[0]
# convert to float (optional)
desired_value = float(desired_value)
print("weight: " + desired_value)
我刚刚看到您更新了代码并使用了 numpy - 没有您的输入数据,我想您想要类似的东西
data = np.loadtxt("mercurial.ini", max_rows=1, dtype=np.str, comments="c").item(0)
value = data.split("\t")[-1].split(" kg")[0]
print("weight: " + value)
如果您的字符串不是制表符分隔等,您可能不得不使用 split 参数。
如果您在阅读后打印该W_txt
,您会看到
['#' 'data1' 'data2' 'data3' 'W' '=' '10.251' 'kg']
您正在尝试读取不存在的索引 8 处的数据。 您应该使用读取重量数据
weight_txt = W_txt[6]
至于那些警告,正如它所说,不推荐使用np.float
,请改用float
:
weight = weight_txt.astype(float)
所以,整个代码应该是这样的:
import numpy as np
W_txt = np.loadtxt('./data.txt', max_rows=1, dtype=str, comments='c')
weight_txt = W_txt[6]
weight = weight_txt.astype(float)
print(weight)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.