Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- input_file = 'actual_tests_pmp_topic1.txt' # Path to your input text file
- output_file = 'actual_tests_pmp_topic1.csv' # Path to the output CSV file
- # Open the input text file for reading
- with open(input_file, 'r') as file:
- lines = file.readlines()
- # Open the output CSV file for writing
- with open(output_file, 'w', newline='') as file:
- writer = csv.writer(file)
- writer.writerow(['Question', 'Choice A', 'Choice B', 'Choice C', 'Choice D', 'Answer']) # Write the header row
- # Initialize variables to store question, choices, and answer
- question = None
- choices = []
- answer = None
- # Iterate over the lines in the input text file
- for line in lines:
- line = line.strip()
- if line.startswith('QUESTION NO:'):
- # Extract the question number
- question_no = line.split(':')[1].strip()
- elif line and not line.startswith(('A.', 'B.', 'C.', 'D.', 'Answer:')):
- # Start accumulating the question text if it spans multiple lines
- if question is None:
- question = line
- else:
- question += " " + line
- elif line.startswith(('A.', 'B.', 'C.', 'D.')):
- # Extract the choices
- choices.append(line[3:].strip())
- elif line.startswith('Answer:'):
- # Extract the answer
- answer = line.replace('Answer:', '').strip()
- # Check if the question, choices, and answer are all present
- if question and len(choices) == 4 and answer:
- # Write the question, choices, and answer to the CSV file
- writer.writerow([question.strip(), choices[0], choices[1], choices[2], choices[3], answer])
- # Reset the question, choices, and answer variables
- question = None
- choices = []
- answer = None
Advertisement
Add Comment
Please, Sign In to add comment