【问题标题】:How to parse a certain column from a certain line in an ASCII file?如何从 ASCII 文件中的某一行解析某一列?
【发布时间】:2017-03-29 20:29:55
【问题描述】:

我正在尝试从我的 ASCII 文件中某一行的某一列中解析出一个字符串值。下面我已经包含了我到目前为止所尝试的内容,我在运行此代码时收到的错误是:

Attribute: 'list' object has no attribute 'split'`

代码:

import numpy as np
import matplotlib.pyplot as plt

f = open('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 'r')

line = f.readlines(49)
columns = line.split()
time = columns(2)
print (time)

f.close()

【问题讨论】:

  • 列表没有.split() 函数。你想做什么?

标签: python parsing ascii


【解决方案1】:

我会创建一个函数来做到这一点。
请注意,行号和列号从 1 开始计数,而不是从零开始。

def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        for i in range(line_num-1):  # skip over lines before the desired one
            next(file)
        line = next(file)  # read the desired line
        return line.split()[column_num-1]

# sample usage
print(find_line_and_column('zz_ssmv11034tS__T0001TTNATS2012021505HP001.Hdr', 4, 3))

或者,在itertools 模块中使用islice() 函数可以更简洁地完成它:

import itertools

def find_line_and_column(filename, line_num, column_num):
    with open(filename, 'r') as file:
        line = next(itertools.islice(file, line_num-1, None), None) # get line_num-th line
        return line.split()[column_num-1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多