从TSV文件中提取数据 Python

0 投票
2 回答
3475 浏览
提问于 2025-04-18 18:38

我有一个TSV文件,内容大概是这样的:

A   B   C   D   D=1;E=2
S   D   F   G   H=2;B=4

我想把这些内容写入另一个TSV文件,格式是这样的。

A   B   C   D   D   1
A   B   C   D   E   2
S   D   F   G   H   2
S   D   F   G   B   4

如果有人能帮我或者给我一些提示,教我怎么把第5列分开,我会非常感激。

2 个回答

3
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    for line in csv.reader(infile, delimiter='\t'):
        vals = line[-1]
        headers = line[:-1]
        for val in vals.split(';'):
            writer.writeline(headers + [val])

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

1

如果你确定你的数据里只有制表符和分号,那你可以用分割的方法。

with open('/tmp/test.tsv') as infile, open('/tmp/test2.tsv', 'w') as outfile:
    for line in infile:
        tsplit = line.split("\t")
        firstcolumns = tsplit[:-1]
        lastitems = tsplit[-1].strip().split(";")
        for item in lastitems:
            allcolumns = firstcolumns + item.split("=")
            outfile.write("\t".join(allcolumns) + "\n")

(更新了内容,让它更容易和其他答案进行比较。)

这个方法不管你最后一列有多少个用分号分开的项目都能用。不过,它对格式的小变化很敏感(比如多了空格)。

撰写回答