2016-06-16 2 views
-2

나는이파이썬 프로그램

Steve 
Mark 
Sarah 
같은 별도의 줄에 각 파일 이름을 포함, 텍스트 파일의 각 이름을 n 개의 소요 파이썬 프로그램을 작성하는 것을 시도하고있다

프로그램에서 수행하는 작업은 입력 된 모든 파일에있는 이름 만 인쇄하는 것입니다. 저는이 아이디어를 구현하는 방법을 모르기 때문에 프로그래밍에 익숙하지 않지만 재귀에서 생각한 것처럼 프로그램이 무한 루프에서 실행되는 것처럼 보입니다. 문제가 무엇인지 확실하지 않습니다. 구현이 잘못 되었습니까? 그렇다면 구현 방법에 대해 더 잘 알고 있습니까?

import sys 
arguments = sys.argv[1:] 
files = {} 

file = iter(arguments) 
for number in range(len(sys.argv[1:])): 
    files[number] = open(next(file)) 

def close_files(): 
    for num in files: 
     files[num].close() 


def start_next_file(line,files,orderOfFile): 
    print('starting next file') 
    if orderOfFile < len(files): # to avoid IndexError 
     for line_searched in files[orderOfFile]: 
      if line_searched.strip(): 
       line_searched = line_searched[:-1] 
       print('searched line = '+line_searched) 
       print('searched compared to = ' + line) 
       if line_searched == line: 
        #good now see if that name exists in the other files as well 
        start_next_file(line,files,orderOfFile+1) 

    elif orderOfFile >= len(files): # when you finish searching all the files 
     print('got ya '+line) #print the name that exists in all the files 
     for file in files: 
      # to make sure the cursor is at the beginning of the read files 
      #so we can loop through them again 
      files[file].seek(0) 



def start_find_match(files): 
    orderOfFile = 0 
    for line in files[orderOfFile] : 
     # for each name in the file see if it exists in all other files 
     if line.strip(): 
      line = line[:-1] 
      print ('starting line = '+line) 
      start_next_file(line,files,orderOfFile+1) 



start_find_match(files) 
close_files() 
+0

모든 텍스트 파일? – Jarad

+0

@ 자라드 예, 그들은 –

답변

0

정확하게 코드를 수정하는 방법을 모르겠지만 여기에 대해 생각해 보는 것이 좋습니다.

listdir은 디렉토리의 모든 파일을 목록으로 가져옵니다. 이를 .txt 파일로만 좁 힙니다. 다음으로 개행을 읽고, 읽고, 나누고, 더 낮은 이름을 포함하는 목록을 만드십시오. 따라서 files은 목록의 목록입니다. 마지막으로 일부 set 논리를 사용하여 모든 목록에서 교차 부분을 찾습니다.

import os 

folder = [f for f in os.listdir() if f[-4:] == '.txt'] 
files = [] 

for i,file in enumerate(folder): 
    with open(file) as f: 
    files.append([name.lower() for name in f.read().splitlines()]) 

result = set.intersection(*map(set, files)) 

예 :

#file1.txt 
john 
smith 
mary 
sue 
pretesh 
ashton 
olaf 
Elsa 

#file2.txt 
David 
Lorenzo 
Cassy 
Grant 
elsa 
Felica 
Salvador 
Candance 
Fidel 
olaf 
Tammi 
Pasquale 

#file3.txt 
Jaleesa 
Domenic 
Shala 
Berry 
Pamelia 
Kenneth 
Georgina 
Olaf 
Kenton 
Milly 
Morgan 
elsa 

반환 : 하나의 디렉토리에

{'olaf', 'elsa'}