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

时间:2019-02-08 21:16:44

标签: python pandas dataframe readlines

我使用python 3,我读取了几行包含文本和数字的行,并且从某一行开始只有几列数字,最初它们在拆分后也被读取为str,后来我将其转换为他们漂浮。

数据如下所示。我还将链接添加到数字示例

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

enter image description here

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

ValueError除外

但是这确实不起作用!

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,然后继续进行拆分,但我不知道怎么做

1 个答案:

答案 0 :(得分:1)

您应该尝试一下。该代码使用正则表达式以一种干净的方式查找数据。

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