Connecting Tech Pros Worldwide Forums | Help | Site Map

Improve my Functions?

Newbie
 
Join Date: Nov 2006
Posts: 10
#1: Nov 22 '06
Trying to set up a file for questions and answers. Doesn't seem to be working properly. Can anyone see where I can improve my functions? This is what I have so far:


questionFile = open('questions.txt')
numberQuestionDictionary = {}
for line in questionFile.readlines():
if not line:
continue
line = line.strip()
if len(line) == 0:
continue
numberAndQuestion = line.split('.')
number = numberAndQuestion[0]
question = numberAndQuestion[1].strip()
numberQuestionDictionary[number] = question
questionFile.close()

answerFile = open('answers.txt')
numberAnswerDictionary = {}
for line in answerFile.readlines():
if not line:
continue
line = line.strip()
if len(line) == 0:
continue
numberAndAnswer = line.split('.')
number = numberAndAnswer[0]
answer = numberAndAnswer[1].strip()
numberAnswerDictionary[number] = answer
answerFile.close()

for number in numberQuestionDictionary.keys():
print 'Q: ',
print numberQuestionDictionary[number]
print 'A: ',
print numberAnswerDictionary[number]
print

bartonc's Avatar
Moderator
 
Join Date: Sep 2006
Location: Minden, Nevada, USA
Posts: 6,400
#2: Nov 22 '06

re: Improve my Functions?


What you have so far looks OK. The files that you are reading must be in the same directory as this module. You must read the gray writing on the background of the post window or the "Posting Guidelines" on the right or at the top of this forum to learn how to use CODE TAGS so that your post looks like this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. # Read number and question from a file into a dict
  3. questionFile = open('questions.txt')
  4. numberQuestionDictionary = {}
  5. for line in questionFile.readlines():
  6.     if not line:
  7.         continue
  8.     line = line.strip()
  9.     if len(line) == 0:
  10.         continue
  11.     numberAndQuestion = line.split('.')
  12.     number = numberAndQuestion[0]
  13.     question = numberAndQuestion[1].strip()
  14.     numberQuestionDictionary[number] = question
  15. questionFile.close()
  16. # Read number and answer from a file into a dict
  17. answerFile = open('answers.txt')
  18. numberAnswerDictionary = {}
  19. for line in answerFile.readlines():
  20.     if not line:
  21.         continue
  22.     line = line.strip()
  23.     if len(line) == 0:
  24.         continue
  25.     numberAndAnswer = line.split('.')
  26.     number = numberAndAnswer[0]
  27.     answer = numberAndAnswer[1].strip()
  28.     numberAnswerDictionary[number] = answer
  29. answerFile.close()
  30.  
  31. for number in numberQuestionDictionary.keys():
  32.     print 'Q: ',
  33.     print numberQuestionDictionary[number]
  34.     print 'A: ',
  35.     print numberAnswerDictionary[number]
  36.     print
  37.  
We'll also need a copy of the text files that you are trying to read. Thanks for posting,
Barton
Reply