pranaman

Untitled

Jul 7th, 2023
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import csv
  2.  
  3. input_file = 'actual_tests_pmp_topic1.txt' # Path to your input text file
  4. output_file = 'actual_tests_pmp_topic1.csv' # Path to the output CSV file
  5.  
  6. # Open the input text file for reading
  7. with open(input_file, 'r') as file:
  8. lines = file.readlines()
  9.  
  10. # Open the output CSV file for writing
  11. with open(output_file, 'w', newline='') as file:
  12. writer = csv.writer(file)
  13. writer.writerow(['Question', 'Choice A', 'Choice B', 'Choice C', 'Choice D', 'Answer']) # Write the header row
  14.  
  15. # Initialize variables to store question, choices, and answer
  16. question = None
  17. choices = []
  18. answer = None
  19.  
  20. # Iterate over the lines in the input text file
  21. for line in lines:
  22. line = line.strip()
  23.  
  24. if line.startswith('QUESTION NO:'):
  25. # Extract the question number
  26. question_no = line.split(':')[1].strip()
  27.  
  28. elif line and not line.startswith(('A.', 'B.', 'C.', 'D.', 'Answer:')):
  29. # Start accumulating the question text if it spans multiple lines
  30. if question is None:
  31. question = line
  32. else:
  33. question += " " + line
  34.  
  35. elif line.startswith(('A.', 'B.', 'C.', 'D.')):
  36. # Extract the choices
  37. choices.append(line[3:].strip())
  38.  
  39. elif line.startswith('Answer:'):
  40. # Extract the answer
  41. answer = line.replace('Answer:', '').strip()
  42.  
  43. # Check if the question, choices, and answer are all present
  44. if question and len(choices) == 4 and answer:
  45. # Write the question, choices, and answer to the CSV file
  46. writer.writerow([question.strip(), choices[0], choices[1], choices[2], choices[3], answer])
  47.  
  48. # Reset the question, choices, and answer variables
  49. question = None
  50. choices = []
  51. answer = None
  52.  
Advertisement
Add Comment
Please, Sign In to add comment