基于特定列中的值拆分值

2024-03-28 09:15:09 发布

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

我有一个文件,我想分为多个文件与uniq值为第一列。例如,下面是一个文件:

你知道吗文件A.txt你知道吗

1    Cat
1    Dog
1    Frog
2    Boy
2    Girl
3    Tree
3    Leaf
3    Branch
3    Trunk

我希望我的输出像这样:

文件1.txt

1    Cat
2    Boy
3    Tree

文件2.txt

1    Dog
2    Girl
3    Leaf

文件3.txt

1    Frog
3    Branch

文件4.txt

3    Trunk

如果值不存在,我希望跳过它。我曾试着寻找与我类似的情况,但我没有成功。有人知道怎么做吗?你知道吗

理论上,这个awk命令应该可以工作:awk '{print > "file" ++a[$1] ".txt"}' input。但是,我无法让它正常工作(很可能是因为我在mac上工作),有人知道其他方法吗?你知道吗


Tags: 文件txtbranchtree情况理论cattrunk
2条回答

下面是Python中的一个解决方案:

from collections import Counter
fd_dict = {}
ind_counter = Counter()

with open('fileA.txt') as inf:
    for line in inf:
        ind, _ = line.split()
        ind_counter[ind] += 1
        file_ind = ind_counter[ind]
        fd = (
            fd_dict[file_ind] if file_ind in fd_dict else
            fd_dict.setdefault(
                file_ind, 
                open('file{}.txt'.format(file_ind), 'w')))
        fd.write(line)

for fd in fd_dict.itervalues():
    fd.close()

输出重定向右侧的未附加表达式是未定义的行为。试试awk '{print > ("file" ++a[$1] ".txt")}' input。你知道吗

如果有太多的文件同时打开是一个问题,那么得到GNU awk,但如果你不能:

$ ls
 fileA.txt

$ awk '{f="file" ++a[$1] ".txt"; print >> f; close(f)}' fileA.txt

$ ls
file1.txt  file2.txt  file3.txt  file4.txt  fileA.txt

$ cat file1.txt
1    Cat
2    Boy
3    Tree

相关问题 更多 >