Python查找第n列以开头的行

2024-09-24 22:26:00 发布

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

我有一个制表符分隔的txt文件,如下所示:

A   B   aaaKP
C   D   bbbZ

这是制表符分隔的。你知道吗

如果

phrase = aaa
column = 3

那么我只想要那些第3列以aaa开头的行

输出将是

A   B   aaaKP

我试过的很乏味,我只试过MatLab。你知道吗

我只能通过使用非常慢的if和for语句和findstr来尝试。你知道吗

我用MatLab找不到更好的方法。你知道吗


Tags: 文件方法txtforifcolumn语句制表符
2条回答
phrase, column = 'aaa', 3
fn = lambda l : len(l) >= column and len(l[column-1]) >= len(phrase) and phrase == l[column-1][:len(phrase)]
fp = open('output.txt', 'w')
fp.write(''.join(row for row in open('input.txt') if fn(row.split('\t'))))
fp.close()

我能想到的最简单的方法是:

with open('tab-delimited.txt', 'r') as f:
    for l in f:
       if l.split('\t')[2][:3] == 'aaa':
            print(l)

如果您需要了解python切片的帮助,请参阅this question。你知道吗

相关问题 更多 >