2013-07-12 144 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"; 
} 
相關問題