题库排版格式化输出
import re
def reformat_keep_question_number(text):
# 按题号拆分:匹配以数字+点开头的新题(保留匹配的位置)
matches = list(re.finditer(r'^\d+\.', text, flags=re.MULTILINE))
question_blocks = []
for i in range(len(matches)):
start = matches[i].start()
end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
block = text[start:end].strip()
question_blocks.append(block)
reformatted_blocks = []
for block in question_blocks:
lines = block.splitlines()
answer_line = next((line for line in lines if line.startswith("答案:")), None)
if answer_line:
lines.remove(answer_line)
lines.append(answer_line) # 加到最后一行
clean_lines = [line for line in lines if line.strip() and not line.strip().isdigit()]
reformatted_blocks.append('\n'.join(clean_lines))
return '\n\n'.join(reformatted_blocks)
# 示例用法
if __name__ == "__main__":
with open("input.txt", "r", encoding="utf-8") as f:
raw_text = f.read()
result = reformat_keep_question_number(raw_text)
with open("output.txt", "w", encoding="utf-8") as f:
f.write(result)
print("处理完成,结果保存在 output.txt")
input:
一、单选(1-540)
1.为了保障( ),维护网络空间主权和国家安全、社会公共利益,保护公民、法人和其他组织的合法权益,促进经济社会信息化健康发展,制定本法。
A.网络自由
B.网络速度
C.网络安全
D.网络信息
答案:C
2.在中华人民共和国境内建设、运营、( )和使用网络,以及网络安全的监督管理,适用本法。
答案:A
A.维护
B.运维
C.运营
D.建设
3.国家坚持网络安全与信息化发展并重,遵循积极利用、科学发展、( )、确保安全的方针。
答案:B
A.科学发展
B.依法管理
C.确保安全的方针
D.积极利用
output:
1.为了保障( ),维护网络空间主权和国家安全、社会公共利益,保护公民、法人和其他组织的合法权益,促进经济社会信息化健康发展,制定本法。
A.网络自由
B.网络速度
C.网络安全
D.网络信息
答案:C
2.在中华人民共和国境内建设、运营、( )和使用网络,以及网络安全的监督管理,适用本法。
A.维护
B.运维
C.运营
D.建设
答案:A
3.国家坚持网络安全与信息化发展并重,遵循积极利用、科学发展、( )、确保安全的方针。
A.科学发展
B.依法管理
C.确保安全的方针
D.积极利用
答案:B
评论区