2013-04-06 1 views
0
while True: 
    try: 
     OpenFile=raw_input(str("Please enter a file name: ")) 
     infile=open(OpenFile,"r") 
     contents=infile.readlines() 
     infile.close() 

     user_input = raw_input(str("Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n")) 
     if user_input.startswith("A="): 
      def find_animal(user_input,column): 
       return next(("\t".join(line) for line in contents 
          if line[column-1]==user_input),None) 
      find_animal(user_input[1:]) 
      print str((find_animal(user_input[1:], "WHO?"))) #"Who?" is the name of the first column. 

     else: 
      print "Unknown option!" 


    except IOError: 
     print "File with this name does not exist!" 

1. 동물의 이름을 입력하십시오.탭으로 구분 된 열 파일의 파이썬 검색 기능

2. 프로그램은 첫 번째 열에이 특정 이름을 가진 행을 검색합니다.

3. 프로그램은 첫 번째 열에이 이름을 가진 행을 인쇄합니다.

내 기능이 제대로 작동하지 않는 것 같습니다. 실수를 찾도록 도와 주시겠습니까? 고맙습니다!

편집

 def ask_for_filename(): 
     filename=str(raw_input("Please enter file name: ")) 
     return filename 

     def read_data(filename): 
     contents=open(filename,"r") 
     data=contents.read() 
     return data 

     def column_matches(line, substring, which_column): 
     for line in data: 
      if column_matches(line, substring, 0): 
       print line 
코드의
+0

문자열에''STR()를 호출 할 필요가 없습니다. – poke

답변

0

큰 덩어리 읽기 및 디버그, 다음과 같은 예를 들어, 작은 함수로 코드를 분할 시도하기 어려운 :

def ask_for_filename(): 
    #left as an exercise 
    return filename 

def read_data(filename): 
    #left as an exercise 
    return data 

def column_matches(line, substring, which_column): 
    #left as an exercise 

def show_by_name(name, data): 
    for line in data: 
     if column_matches(line, name, 0): 
      print line 

def do_search(data): 
    propmt = "Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n" 
    user_input = raw_input(prompt) 
    if user_input.startswith('A='): 
     show_by_name(user_input[2:], data) 

# main program 

filename = ask_for_filename() 
data = read_data(filename) 
while True: 
    do_search(data) 

테스트 및 디버그 이러한 기능 제대로 작동 할 때까지는 별도로 그런 다음 주 프로그램을 작성하고 테스트하십시오.

column_matches()

line 일부 열 ( which_column)이 substring 동일한 경우 true를 반환하기로한다. 예를 들어 column_matches("foo\tbar\tbaz", "bar", 1)True입니다.

  • 구분 기호로 줄을 나눌 것을 달성하기 -이
  • 그들이 경우
  • 반환 진정한
  • 가 substing과 비교리스트의 n 번째 요소를 얻을 우리에게 값의 목록을 제공합니다 평등하고, 그렇지 않으면

거짓은 모두 함께 퍼팅 :

def column_matches(line, substring, which_column): 
    delimiter = '\t' 
    columns = line.split(delimiter) 
    value = columns[which_column] 
    if value == substring: 
     return True 
    else: 
     return False 
는 "파이썬"더 간결하고 형태

또는 :

def column_matches(line, substring, which_column): 
    return line.split('\t')[which_column] == substring 
+0

도움 주셔서 감사합니다. 연습을 끝내려고했지만 세 번째 기능에서해야 할 일을 실제로 이해할 수 없습니다. 내가해야 할 일을 설명해 주실 수 없습니까? – meowtwo

+0

@AlButter : 자세한 내용을 추가했습니다. – georg

+0

도움을 주셔서 감사합니다. 이제는 제대로 작동하는 법을 완전히 이해했습니다. Btw, 철저히 단계별 설명과 함께 좋은 파이썬 과정을 조언하시기 바랍니다 수 있습니까? – meowtwo

관련 문제