从字典中提取数据

2024-04-24 02:50:32 发布

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

我有两个制表符分隔的文件,文件1包含标识符,文件2包含与这些标识符相关的值(或者说它是一个非常大的字典)。在

文件1

Ronny
Rubby
Suzie
Paul

文件1只有一列。在

文件2

^{pr2}$

n文件2中有n行。在

我想要的是,如果文件1的标识符存在于文件2中,那么我应该在另一个以制表符分隔的文件中包含与它相关的所有值。在

像这样:

Paul Ronny Rubby Suzie
12     11   11   12
23     12   8.9  5.1

提前谢谢你。在


Tags: 文件字典标识符制表符paulpr2ronnysuzie
3条回答

只能使用bash来执行此操作:

FIELDS=`head -1 f2.txt | tr "\t" "\n" | nl -ba | grep -f f1.txt | cut -f1 | tr -d " " | tr "\n" ","`; FIELDS=${FIELDS/%,/}
cut -f$FIELDS f2.txt 
Paul    Ronny   Ruby    Suzie
12  11  11  12
23  12  8.9 5.1

注意

您的示例输出不正确,因为这里有“Ruby”,但在file1示例中,您的“Rubby”Ruby=/=Rubby

kent$  awk 'NR==FNR{t[$0]++;next}
{if(FNR==1){
        for(i=1;i<=NF;i++)
                if($i in t){
                        v[i]++;
                        printf $i"\t";
                }
        print "";
        }else{
        for(x in v)
                printf $x"\t"
        print "";
}

}' file1 file2

输出

^{pr2}$

Python中一个在流中执行工作的示例(即:在开始输出之前不需要加载完整的文件):

# read keys
with open('file1', 'r') as fd:
    keys = fd.read().splitlines()

# output keys
print '\t'.join(keys)

# read data file, with header line and content
with open('file2', 'r') as fd:
    headers = fd.readline().split()
    while True:
        line = fd.readline().split()
        if len(line) == 0:
            break
        print '\t'.join([line[headers.index(x)] for x in keys if x in headers])

输出:

^{pr2}$

相关问题 更多 >