您的位置:首页 > 新闻 > 会展 > Python小工具—txt转excel和word

Python小工具—txt转excel和word

2025/3/10 18:29:08 来源:https://blog.csdn.net/weixin_55144746/article/details/140449988  浏览:    关键词: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_answersheet.cell(row=row, column=2).value = current_answerrow += 1# 保存答案文本,并重置current_questioncurrent_answer = line[len('答案'):].strip()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com