将文本数据写入边界之间的数组

2024-05-21 02:32:19 发布

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

我有个问题,希望你能帮我解决!我有一个txt,看起来像:

A100 1960  
 3   5  
 6   7  
 8   9  
 10  11  
 12  13  
A200 1960  
 3   5  
 6   7  
 8   9  
 10  11  
 12  13  
 14  15    
A300 1960  
 3   5  
 6   7  
 8   9  
 10  11  
 12  13  
 14  15  
 16  17   

我想搜索关键字,例如A200 1960。现在我想把A200 1960A300 1960之间的所有数字保存在array(x, y)中。你知道吗

我设法跳到了我想要的那一行。现在的问题是写入数组直到第A300 1960行。数组的长度也可以变化。你知道吗

def readnumbers(filename,number,year):
    number_year = np.asarray([])

    f = open(filename)
    lines = f.readlines()
    f.close()

    strings_number = 'A'+ str(number)
    strings_year = ' ' + str(year)

    STARTER = strings_number+ '' + strings_year
    start_seen = False

    for line in lines:
        if line.strip() == STARTER:
            start_seen = True
            continue

        if start_seen == True:
            parts = line.split()

Tags: truenumberifline数组filenameyearstart
3条回答
filename = 'test.txt'

def fill_array():
    f = open(filename)
    lines = f.readlines()
    f.close()
    lines = [x.strip() for x in lines]
    search_term = 'A200 1960'
    read = False
    array = []
    for index in xrange(0,len(lines)):
        if lines[index] == search_term:
            read = True
        elif read: 
            data =  [x.strip() for x in lines[index].split(' ') if x]
            if str(data[0]).isdigit(): 
                array.append(data)
            else: 
                read = False
    print array

数组将包含要保存的数字 输出
[['3', '5'], ['6', '7'], ['8', '9'], ['10', '11'], ['12', '13'], ['14', '15']]

设置start_seen后,使用标准list存储每一行。还要检查每一行是否是“STOPPER”行,这样就可以停止对文件的迭代。你知道吗

此外:

  • 一定要返回结果,否则什么也得不到。你知道吗
  • 使用with语句打开文件,这样就不必手动关闭它。你知道吗
  • 不要使用readlines(),而是直接遍历文件句柄。你知道吗
  • 不要勾选if variable == True:,只要勾选if variable:
def readnumbers(filename,number,year):
    strings_number = 'A'+ str(number)
    strings_year = ' ' + str(year)
    STARTER = strings_number + '' + strings_year

    result = []
    with open(filename) as f:
        start_seen = False

        # iterate the file handle
        for line in f:
            # only check the line for STARTER if you haven’t seen it yet
            if not start_seen and line.strip() == STARTER:
                start_seen = True

            # otherwise, check if it’s a stopper which starts with `A`
            elif start_seen and line.startswith('A'):
                break

            # otherwise, if we’ve seen the start line, we need to capture the result
            elif start_seen:
                parts = line.split()

                # append to the result list
                result.append(parts)

    # finally, return the result
    return result

试试这个:

import sys

start = sys.argv[2] # 'A200 1960'
end = sys.argv[3]   # 'A300 1960'

coords = []         # collected (x, y) tuples
start_seen = False  # Have we seen start yet?
end_seen = False    # Have we seen end yet?

with open(sys.argv[1]) as f:
    for row in f:
        if row.startswith(start):
            start_seen = True
            continue
        if row.startswith(end):
            end_seen = True
            continue
        if start_seen and not end_seen:
            # Split the line and convert each part into an int.
            x, y = [int(s) for s in row.split()]
            coords.append((x, y))

print(coords)

用法:

$ python3.4 so.py data.csv 'A200 1960' 'A300 1960'

输出:

[(3, 5), (6, 7), (8, 9), (10, 11), (12, 13), (14, 15)]

相关问题 更多 >