Python小工具—txt转excel和word

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_answer
            sheet.cell(row=row, column=2).value = current_answer
            row += 1
        # 保存答案文本,并重置current_question
        current_answer = line[len('答案'):].strip()
  
上一篇:Classifier-Free Guidance (CFG) Scale in Stable Diffusion


下一篇:实践致知第16享:设置Word中某一页横着的效果及操作-三、拓展思考