【问题标题】:Skip lines with strange characters when I read a file读取文件时跳过带有奇怪字符的行
【发布时间】:2020-01-03 12:38:35
【问题描述】:

我正在尝试读取一些数据文件“.txt”,其中一些包含奇怪的随机字符,甚至随机行中的额外列,如下例所示,其中第二行是右行的示例:

CTD 10/07/30 05:17:14.41 CTD 24.7813, 0.15752, 1.168, 0.7954, 1497.¸ 23.4848, 0.63042, 1.047, 3.5468, 1496.542

CTD 10/07/30 05:17:14.47 CTD 23.4846、0.62156、1.063、3.4935、1496.482

我阅读了 np.loadtxt 的描述,但没有找到解决问题的方法。是否有系统的方法来跳过这样的行?

我用来读取文件的代码是:

#Function to read a datafile

def Read(filename):
    #Change delimiters for spaces
    s = open(filename).read().replace(':',' ')
    s = s.replace(',',' ')
    s = s.replace('/',' ')
    #Take the columns that we need
    data=np.loadtxt(StringIO(s),usecols=(4,5,6,8,9,10,11,12))
    return data

【问题讨论】:

  • 您能提供您的代码示例吗?

标签: python-3.x numpy io


【解决方案1】:

这无需像其他答案那样使用 csv,而是逐行读取,检查它是否为 ascii

data = []

def isascii(s):
    return len(s) == len(s.encode())

with open("test.txt", "r") as fil:
    for line in fil:
        res = map(isascii, line)
        if all(res):
            data.append(line)

print(data)

【讨论】:

    【解决方案2】:

    您可以使用 csv 模块一次读取一行文件并应用所需的过滤器。

    import csv
    
    def isascii(s):
        len(s) == len(s.encode())
    
    with open('file.csv') as csvfile:
         csvreader = csv.reader(csvfile)
        for row in csvreader:
             if len(row)==expected_length and all((isascii(x) for x in row)):
                 'write row onto numpy array'
    

    我从这个线程得到了 ascii 检查 How to check if a string in Python is in ASCII?

    【讨论】:

    • 除了使用 CSV 之外,您难道不能只逐行读取文件并进行 isascii 检查吗? with open("file.txt", "r") as ins: array = [] for line in ins:
    • 当然,但是 OP 说他们遇到了意外列的问题,而且他们的数据似乎是 csv,所以这是我能想到的检查一行中列数的最标准方法csv 除了 ascii 检查。
    猜你喜欢
    • 2016-08-21
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多