![](/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.