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]
可以使用Python文件读写和字符串处理操作来提取txt指定内容。具体步骤如下: 1. 打开txt文件,使用Python的`open()`函数实现,可以指定文件的读写模式('r'表示读取模式)和编码格式(如'utf-8')。 ```python with open('example.txt', 'r', encoding='utf-8') as f: # do something with the file ``` 2. 读取txt文件内容,可以使用`read()`或`readlines()`方法。`read()`方法将整个文件作为一个字符串读入内存,`readlines()`方法则将每一行作为一个字符串读入内存,并返回一个列表。 ```python # read the entire file contents = f.read() # read the file line by line lines = f.readlines() ``` 3. 对读取到的内容进行处理,可以使用Python的字符串操作函数(如`find()`、`index()`、`split()`、`replace()`等)或正则表达式(使用Python的`re`模块)。 例如,如果要提取txt文件包含特定关键字的行,可以使用如下代码: ```python keyword = 'apple' with open('example.txt', 'r', encoding='utf-8') as f: for line in f: if keyword in line: print(line) ``` 如果要提取txt文件某个特定位置的字符或字符串,可以使用如下代码: ```python with open('example.txt', 'r', encoding='utf-8') as f: contents = f.read() start = contents.find('start') + len('start') end = contents.find('end') result = contents[start:end] print(result) ``` 以上是提取txt指定内容的基本步骤,具体实现要根据具体需求进行调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值