2013-07-12 102 views

回答

0

Python soluti上。

import sys 

with open('file1.txt') as f: 
    d = {line.split()[0]: line for line in f if line.strip()} 

with open('file2.txt') as f: 
    sys.stdout.writelines(d.get(line.strip(), '') for line in f) 
+0

糟糕,蟒蛇标签。 ) – falsetru

+0

给错误 线4,在 d = {line.split()[0]:线在F线} 文件 “sort.py”,第4行,在 d = { line.split()[0]:line for line in f} IndexError:列表索引超出范围 –

+0

@ bio-code's,我更新了代码以跳过空白行。再试一次。 – falsetru

0

Perl解决方案。

#!/usr/bin/perl 

use strict; 
use autodie; 

my %d; 
{ 
    open my $fh, "File2.txt"; 
    while(<$fh>) { 
     chomp; 
     $d{$_} = 1; 
    } 
} 

{ 
    open my $fh, "File1.txt"; 
    while(<$fh>) { 
     my($f1) = split /\s+/, $_; # or alternatively match with a regexp 
     print $_ if $d{$f1}; 
    } 
} 

__END__ 
0

我的Perl解决方案

#! /usr/bin/perl -w 
use strict; 
use warnings; 


open FILE1, "File1.txt" || die "Cannot find File1.txt"; 
open FILE2, "File2.txt" || die "Cannot find File2.txt"; 

my %hash; 

while (<FILE1>) { 
    chomp; 
    my ($key, $value) = split; 

    $hash{$key} = $value; 
} 

while (<FILE2>) { 
    chomp; 
    my $key = $_; 
    print "$key $hash{$key}\n"; 
} 
相关问题