1.txt轉excel
import openpyxl# 創建一個新的Excel工作簿
wb = openpyxl.Workbook()
sheet = wb.active# 題干和答案的標題
sheet['A1'] = '題干'
sheet['B1'] = '答案'# 打開txt文件并讀取內容
with open('xiti.txt', 'r', encoding='utf-8') as file:lines = file.readlines()# 初始變量
current_question = []
current_answer = ''
row = 2 # 從第二行開始寫入數據# 遍歷文件內容
for line in lines:line = line.strip() # 去除每行的兩端空白字符if line.startswith('答案'):# 遇到答案關鍵字,保存當前題干if current_question:question_text = '\n'.join(current_question)sheet.cell(row=row, column=1).value = question_text# 保存當前答案,并重置current_answersheet.cell(row=row, column=2).value = current_answerrow += 1# 保存答案文本,并重置current_questioncurrent_answer = line[len('答案'):].strip()