如何避免在拆分前同时包含字符串和数字的行?

2024-03-28 12:02:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python3,我读取的文件中有几行包含文本和数字,从某一行开始只有数字列,最初它们在拆分后也被读取为str,后来我将它们转换为float。你知道吗

数据是这样的。我还添加了数字示例的链接

https://gist.github.com/Farzadtb/b0457223a26704093524e55d9b46b1a8

enter image description here

所以问题是,对于阅读,我有两个条件(实际上我希望增加这些条件)使用try:except。但这只适用于分割方法。但在开始拆分之前,我需要删除包含文本的第一行。我知道我应该用

除了值错误

但这真的不管用!你知道吗

f = io.open(file, mode="r", encoding="utf-8")
    #f=open(file,"r")
    lines=f.readlines()

    x=[]
    y=[]
    z=[]    

    for i in lines:

        try:
            a=[i.strip('\n')]
            a1=[float(n) for n in a[0].split(',')]
            atot.append(a1)
            x.append(a1[3])
            y.append(a1[2])
            z.append(a1[1])

        except :
             a=[i.split('\n')]
             a1=[float(n) for n in a[0].split()]
             x.append(a1[3])
             y.append(a1[2])
             z.append(a1[1])

问题是,由于第一行也可以以数字开头,所以第一个参数可能被拆分并添加到“x”和“y”中,但我得到的z是错误的

x=[float(i) for i in x]
y=[float(i) for i in y]
z=[float(i) for i in z]

我想到的一个想法是,检查是否可以将行转换为无错误的float,然后继续拆分,但我不知道怎么做


Tags: in文本fora1错误数字openfloat
1条回答
网友
1楼 · 发布于 2024-03-28 12:02:08

你应该试试这个。这段代码使用regexp以干净的方式查找数据。你知道吗

import pprint
import re

if __name__ == '__main__':
    # pattern to ignore line containing alpha or :
    ignore_pattern = re.compile(r'[^a-zA-Z:]*[a-zA-Z:]')
    # number pattern
    number_pattern = re.compile(r'[-.\d]+')

    matrix = []

    # open the file as readonly
    with open('data.txt', 'r') as file_:

        # iterator over lines
        for line in file_:
            # remove \n and spaces at start and end
            line = line.strip()
            if not ignore_pattern.match(line):

                found = number_pattern.findall(line)
                if found:
                    floats = [float(x) for x in found]
                    matrix.append(floats)

    # print matrix in pretty format
    pp = pprint.PrettyPrinter()
    pp.pprint(matrix)

    # access value by [row][column] starting at 0
    print(matrix[0][2])

测试你的样本数据。 这是python脚本的标准输出:

[[-3.1923, 0.6784, -4.6481, -0.0048, 0.3399, -0.2829, 0.0, 24.0477],
 [-3.1827, 0.7048, -4.6257, 0.0017, 0.3435, -0.2855, 0.0, 24.0477],
 [-3.1713, 0.7237, -4.5907, 0.0094, 0.3395, -0.2834, 0.0, 24.0477]]
-4.6481

相关问题 更多 >