저는 Python을 처음 접했고 누군가가 비교적 간단한 Perl 스크립트의 예를 Python으로 친절하게 변환 할 수 있는지 알고 싶습니다.Perl 스크립트를 Python으로 변환 : 해시 키 기반의 파일 2 개를 중복 제거
스크립트는 2 개의 파일을 사용하고 해시 키를 비교하여 두 번째 파일에서 고유 한 줄만 출력합니다. 또한 파일에 중복 행을 출력합니다. 필자는이 중복 제거 방법이 Perl과 매우 빠르며 Python이 어떻게 비교되는지보고 싶습니다.
#! /usr/bin/perl
## Compare file1 and file2 and output only the unique lines from file2.
## Opening file1.txt and store the data in a hash.
open my $file1, '<', "file1.txt" or die $!;
while (<$file1>) {
my $name = $_;
$file1hash{$name}=$_;
}
## Opening file2.txt and store the data in a hash.
open my $file2, '<', "file2.txt" or die $!;
while (<$file2>) {
$name = $_;
$file2hash{$name}=$_;
}
open my $dfh, '>', "duplicate.txt";
## Compare the keys and remove the duplicate one in the file2 hash
foreach (keys %file1hash) {
if (exists ($file2hash{$_}))
{
print $dfh $file2hash{$_};
delete $file2hash{$_};
}
}
open my $ofh, '>', "file2_clean.txt";
print $ofh values(%file2hash) ;
필자는 perl과 python 스크립트를 1 백만 라인이 넘는 2 개의 파일에서 테스트했으며 총 시간은 6 초 미만이었습니다. 이 사업 목적을 위해 성능이 뛰어납니다!
나는 크리스가 제공하는 스크립트를 수정하고 난 둘 다 결과에 매우 행복하다 : 1) 내가 스크립트를 수정있는 스크립트의 성능과 2) 용이성을 더 유연하게 :
#!/usr/bin/env python
import os
filename1 = raw_input("What is the first file name to compare? ")
filename2 = raw_input("What is the second file name to compare? ")
file1set = set([line for line in file(filename1)])
file2set = set([line for line in file(filename2)])
for name, results in [
(os.path.abspath(os.getcwd()) + "/duplicate.txt", file1set.intersection(file2set)),
(os.path.abspath(os.getcwd()) + "/" + filename2 + "_clean.txt", file2set.difference(file1set))]:
with file(name, 'w') as fh:
for line in results:
fh.write(line)
여러분이 알고있는 것과 질문이 무엇인지 알 수 있도록 여러분의 파이썬 노력을 게시하십시오. –