2014-10-29 3 views
-1

큰 파일 두 개를 비교해야하지만 성능과 관련된 몇 가지 문제가 있습니다.파이썬에서 두 파일을보다 효율적으로 비교하려면 어떻게해야합니까?

는 자, 두 개의 파일 XY를 생각해 보자.

X에는 42000 개의 레코드가 있습니다. 한 줄에 한 단어 씩.

Y은 881000을 갖는다. 라인 당 3 워드, 즉 3 개의 컬럼.

X 파일의 단어와 Y 파일의 첫 번째 단어를 비교하고 싶습니다. 나는 Y_first_column_wordX_word를 발견하면

후 나는 file(Y_second_column_word)Y 파일의 두 번째 컬럼의 단어를 쓰기.

코드 참조 :

to_file = open(output_file, 'w')    # opening the file to write 
f1  = open(input_file1, "rU").readlines() # reading 1st file 42000 records 
f2  = open(input_file2, "rU").readlines() # reading 2nd file 881000 records 

for i, w1 in enumerate(f1): 
    for j, line in enumerate(f2): 
     w2 = line.split(',')      # splitting words from 2nd file 
     if w1.strip() == w2[0].strip():   # removing trails 
      if w2[1].strip() == '':    # when it is blank, get 1st column word 
       w2[1] = w2[0] 
      print>>to_file, w2[1] 

to_file.close()         # closing the file 

내가 수행 한 테스트는 테스트 데이터와 실행을, 그리고 내가 원하는 것을. 그러나 실제 데이터로 실행하면 응답이 없습니다. 나의 마지막 시도는 18 시간을 보냈다.

이 코드를보다 효율적으로 실행하기 위해 개선 할 방법이 있습니까?

답변

4

현재 접근 방식은 O(N**2)입니다. 사전을 사용하여 두 번째 파일의 내용을 저장하면 선형 시간에이를 수행 할 수 있습니다.

with open(input_file1, "rU")as f1, open(input_file2, "rU") as f2: 
    words_dict = {k:v for k, v, _ in (line.split(',') for line in f2)} 
    for word in f1: 
     word = word.rstrip() 
     if word in words_dict: 
      #write words_dict[word] to to_file 
관련 문제