在楼上大佬代码的基础上优化了下,去重判断以题干文字
[Python] 纯文本查看 复制代码 import re
import os
import tkinter as tk
from tkinter import filedialog
# 获取程序所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 文件路径定义(默认设置为程序所在目录)
root = tk.Tk()
root.withdraw() # 隐藏主窗口
# 选择输入文件(默认打开程序所在目录)
input_file = filedialog.askopenfilename(
initialdir=script_dir,
title="选择题目文件",
filetypes=(("文本文件", "*.txt"), ("所有文件", "*.*"))
)
root.destroy()
if not input_file:
print("未选择文件,程序终止。")
exit()
output_dir = script_dir # 输出目录设置为程序所在目录
# 从输入路径提取文件名(带扩展名)
input_basename = os.path.basename(input_file)
# 分割文件名和扩展名(支持多扩展名文件)
filename, ext = os.path.splitext(input_basename)
# 构建新文件名
output_file = os.path.join(output_dir, f"{filename}_去重处理后{ext}")
# 正则表达式匹配题号:数字+点开头
question_start_pattern = re.compile(r'^(\d+)(?:\.|\、)')
seen_questions = set() # 改为存储题干指纹
questions = []
current_question = []
def is_question_start(line):
return question_start_pattern.match(line.strip())
# 读取文件并分块提取题目(ANSI 编码 = gbk)
with open(input_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.rstrip() # 去除右边空格和换行符
if is_question_start(line):
if current_question:
questions.append(current_question)
current_question = []
current_question.append(line)
if current_question:
questions.append(current_question)
# 处理题目:去空行、去重、规范格式
formatted_questions = []
for idx, lines in enumerate(questions, start=1):
# 去掉题号前缀
first_line = lines[0]
# 生成题干指纹(去除题号+首行内容)
clean_first_line = question_start_pattern.sub('', first_line, count=1).strip()
# 构建新题干(去掉原题号,并重新编号为“1、”)
if clean_first_line in seen_questions:
continue
seen_questions.add(clean_first_line)
# 构建新题目
new_question = [f"{idx}、{clean_first_line}"]
for line in lines[1:]:
stripped = line.strip()
if stripped: # 忽略空行
new_question.append(line)
# 添加空行在题干之后
if len(new_question) > 0:
new_question.insert(1, '') # 第二行插入空行
# 转为字符串用于去重
question_str = '\n'.join(new_question)
if question_str not in seen_questions:
seen_questions.add(question_str)
formatted_questions.append(new_question)
# 写入结果文件(使用 UTF-8 编码)
os.makedirs(output_dir, exist_ok=True)
with open(output_file, 'w', encoding='utf-8') as f:
for q in formatted_questions:
f.write('\n'.join(q))
f.write('\n') # 每个题目之间保留一个换行
# 输出重复的题目数量
print(f"处理完成,剔除重复题目 {len(questions) - len(formatted_questions)} 个,输出 {len(formatted_questions)} 道题目。")
# 修改最后的输出提示
print(f"输出文件:{output_file}") |