2014-03-24 4 views
0

저는 Python을 처음 사용하고 질문지 프로그램을 만들었습니다. 각 질문과 선택 사항을 한 번에 하나씩 표시하도록 할 수있는 방법이 있습니까 (이전 선택 질문에 답하지 않는 한 다음 객관식 질문은 표시되지 않습니다)?한 번에 n 줄씩 텍스트 파일 읽기

나는 이것을 수행하기 위해 슬라이싱을 사용했지만 좋은 연습이 아니거나 더 나은 대체 방법이있는 무언가를하고 있는지 궁금합니다.

#opens the file with questions, and is told to read only via 'r' 
with open("PythonQ.txt", "r") as f: 
#reads the file line by line with 'readlines' 
    variable = f.readlines() 
#issue was with no slicing, it was reading letter by letter. so 
#without the slicing and the split, the questions would not print per question 
#the goal by slicing is to get readlines to read per question, not the entire file or first 5 words  
    for line in variable[0:6]: 
#this strips the brackets and splits it by commas only, otherwise it will print both  
     question = line.split(',') 
#joins elements of the list which are separated by a comma 
     print(", ".join(question)) 

choice1 = eval(input("\nYour choice?: ")) 

#sliced for second question. Begins at five to provide room in program between first and second question. 
for line in variable[6:12]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice2 = eval(input("\nYour choice?: ")) 


for line in variable[12:18]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice3 = eval(input("\nYour choice?: ")) 


for line in variable[18:24]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice4 = eval(input("\nYour choice?: ")) 


for line in variable[24:30]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice5 = eval(input("\nYour choice?: ")) 


for line in variable[30:36]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice6 = eval(input("\nYour choice?: ")) 


for line in variable[36:42]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice7 = eval(input("\nYour choice?: ")) 


for line in variable[42:48]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice8 = eval(input("\nYour choice?: ")) 


for line in variable[48:54]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice9 = eval(input("\nYour choice?: ")) 


for line in variable[54:60]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice10 = eval(input("\nYour choice?: ")) 

#add up all the numbers the user typed and assigned it variable x 
x = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8 + choice9 + choice10 

#there are only so high a person's score can go, depending upon if user chose mostly 1's, 2's, 3's or 4's in quiz. 
if x <= 13: 
    print("\n\n\nYour personality and work environment type is...\n \n\n\nRealistic: The 'Doer'\n") 
#another file was created for the results. Import file. Then call the function, CategoryA. 
    import Results 
    Results.CategoryA() 
elif x <= 22: 
    print("\n\n\nYour personality and work environment type is...\n \n\n\nSocial: The Helper\n") 
    import Results 
    Results.CategoryB() 
elif x <= 31: 
    print("\n\n\nYour personality and work environment type is...\n \n\n\nEnterprising: The Persuader\n") 
    import Results 
    Results.CategoryC() 
elif x <= 40: 
    print("\n\n\nYour personality and work environment type is...\n \n\n\nConventional: The Organizer\n") 
    import Results 
    Results.CategorD() 
+2

읽고있는 파일의 예가 있습니까 (PythonQ.txt)? –

+0

OP와 같은데 전체 파일을 읽습니다. 6 행의 객관식 질문의 퀴즈로 구성되어 있습니다. 1) .. 4) :'variable = f.readlines()' – smci

+0

'question = line .split (',')'바로 뒤에'print (",".join (question) "? 불필요한 것 같습니다. – smci

답변

0

다음은 생성기를 사용하여 더 많은 Pythonic 관용구에서 코드를 완전히 다시 작성한 것입니다.

객관식 질문의 여섯 줄 청크 + 색인 된 답변 1)을 포함한 전체 파일을 읽는 것이 문제가되었습니다. 4) : variable = f.readlines(). variablequiz_contents보다 더 나쁜 이름이지만, 무엇이든간에.

그리고 객관식 질문과 답변의 각 6 줄 청크에 개별적으로 액세스하고 싶습니다. readlines()을 사용하고 있었기 때문에 각 청크에 액세스하려면 ','다음에 ','(더 이상 필요하지 않은 것 같은가?)로 결합한 다음 그 이상한 분리를 수행해야합니다.

variable = f.readlines()을 사용하지 마십시오! 이 파일은 전체 파일에서 하나의 거대한 다중 라인 문자열로 분할됩니다. 줄 바꿈 시퀀스 (split new line)이 아닌 readline()을 6 번 연속 호출하여 얻을 수 있습니다. split('\n') 그 줄 바꿈을 할 수 있지만, 처음에는 readlines()을 사용하지 않는 것이 가장 좋습니다. 대신 readline()을 사용하십시오. 질문 당 6 번.

그래서 여기에 아래의 코드를 재 작성에 사용 된 파이썬 방법 : 당신이 그것을 필요로

  • 은 각각 6 줄 덩어리를 읽어 보시기 바랍니다. 파일
  • 주 우리는 각 6 줄 덩어리를 반환하는 get_chunk()의 일종이 필요 print (line, end='') # don't add extra newline
  • 의 사용 내용에 거대한 문자열 버퍼에 대한 필요가 없습니다. 이 경우 생성기는 함수보다 더 우아합니다. 또한 EOF를 감지하고 없음을 반환 할 수 있습니다.
  • 그러면 이제는 for chunk in get_chunk(quiz_contents)이라고 말하기 때문에 호출 코드가 더 우아 해집니다. 생성기에서 None을 얻으면이 for 루프가 종료됩니다.
  • 보조 참고 : get_chunk()은 실제로 각 청크마다 6 + 4 행을 읽어야합니다. 각 청크에 4 개의 여분의 공백 행이 있습니다. 사소하게 제거하고 인쇄물 (...)을 추가 할 수 있습니다.
  • 발전기 내부에서 for-loop 대신 목록 이해력 chunk = [buf.readline() for _ in range(n)]을 사용합니다. 그러나 for-loop를 사용할 수 있습니다. _

quiz_file = './PythonQ.txt' 
num_questions = 10 

def get_chunk(buf, n): 
    """Read n-line chunks from filehandle. Returns sequence of n lines, or None at EOF.""" 

    while buf: 
     chunk = [buf.readline() for _ in range(n)] 

     if not any(chunk): # detect termination at end-of-file (list of ['', '',...]) 
      chunk = None 

     yield chunk 

    # Notes: 
    # This is a generator not a function: we must use 'yield' instead of 'return' to be able to return a sequence of lines, not just one single line 
    # _ is customary Python name for throwaway variable 


with open(quiz_file) as quiz_contents: # Note: quiz_contents is now just a filehandle, not a huge buffer. Much nicer. 

    choices = [None] * num_questions 

    i = 0 

    for chunk in get_chunk(quiz_contents, 6+4): # need to read 6 lines + 4 blank lines 

     if not chunk: 
      break  
     # Don't even need to explicitly test for end-condition 'if i >= num_questions: break' as we just make our generator yield None when we run out of questions 

     print() 
     for line in chunk: 
      print (line, end='') # don't add extra newline 

     choices[i] = int(input("\nYour choice (1-4)?: ")) # expecting number 1..4. Strictly you should check, and loop on bad input 
     i += 1 

     # Don't even need to test for end-condition as we'll just run out of questions 

    score = sum(choices) 
    print('Your score was', score) 

    # do case-specific stuff with score... could write a function process_score(score) 
0

죄송합니다 __, 내가 할 수있는 (우리가 그렇지 않은 경우에 대한 루프 카운터를 검사 결코 우리가 6 계산하기 위해 필요한이 경우 예) 일회용 변수에 대한 관습 파이썬 이름입니다 당신의 질문에 도움이되지 않지만, 나는 원했다. 아직도 나는 물어보고 싶다 : 당신은 9 개의 동일한 코드를 가지고있다.반복

코드 :

for line in variable[6:12]: 
     question = line.split(',') 
     print(", ".join(question)) 

choice2 = eval(input("\nYour choice?: ")) 

9 번 루프를 의미 우리는 나는 모든 비판을 받아 "X"

for i in range(1,10) 
    for line in variable[6*i:6*(i+1)]: 
     question = line.split(',') 
     print(", ".join(question)) 

x+=eval(input("\nYour choice?: ")) 

하는 "choice1을"의 이름을 변경합니다.

관련 문제