Python从txt文件中提取特定数据

本段代码用于,想要从一段txt文件中只提取目标数据的情况。

代码:

def get_data(txt_path: str = '', epoch: int = 100, target: str = '', target_data_len: int = 5):
    num_list = []  # 将提取出来的数据保存到列表,并在最后返回
    data = open(txt_path, encoding="utf-8")  # 打开文件
    str1 = data.read()  # 将文件中读取到的内容转化为字符串
    data.close()  # 关闭文件
    for i in range(0, epoch):
        index = str1.find(target)  # 查找字符串str1中str2字符串的位置
        num_list.append(float(str1[index+len(target):index+len(target)+target_data_len]))  # 将需要的数据提取到列表中
        str1 = str1.replace(target, 'xxxx', 1)  # 替换掉已经查阅过的地方,' xxxx '表示替换后的内容,1表示在字符串中的替换次数为1

    return num_list

函数参数解释:
txt_path 文件路径
epoch 这份文本文件中要提取出的数据个数,默认100
target 目标数据的前缀
target_data_len 目标数据的长度,默认为5
返回值,列表数据

使用举例:

txt文档内容:

x1:273   test3:477    y4:38489   y1:149   x2:423
x1:274   test3:475    y4:37956   y1:152   x2:422
x1:269   test3:473    y4:38156   y1:152   x2:421
x1:271   test3:471    y4:38156   y1:155   x2:418
x1:272   test3:467    y4:38056   y1:158   x2:416
x1:275   test3:466    y4:37956   y1:161   x2:415

使用:

data_path = "D:/program/test/double_camera_data/x_data.txt"

# 提取x1的数据
list_x1  = get_data(data_path, 6, target="x1:", target_data_len=3)

# 提取test3的数据
list_test3  = get_data(data_path, 6, target="test3:", target_data_len=3)

# 提取y4的数据
list_y4  = get_data(data_path, 6, target="y4:", target_data_len=6)

print(list_x1)
print(list_test3)
print(list_y4)

输出:

[273.0, 274.0, 269.0, 271.0, 272.0, 275.0]
[477.0, 475.0, 473.0, 471.0, 467.0, 466.0]
[38489.0, 37956.0, 38156.0, 38156.0, 38056.0, 37956.0]

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年7月6日
下一篇 2023年7月6日

相关推荐