用Tkinter实现高级文本处理软件 _含替换_插入_正则替换等功能
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import re
class TextProcessorApp:
"""主应用程序类,用于创建文本处理软件界面和功能"""
def __init__(self, root):
"""初始化应用程序界面"""
# 设置主窗口
self.root = root
self.root.title("高级文本处理工具") # 设置窗口标题
self.root.geometry("800x600") # 设置窗口大小
# 创建界面组件
self.create_widgets()
def create_widgets(self):
"""创建所有界面组件"""
# 创建主框架容器
main_frame = ttk.Frame(self.root, padding="10") # 添加10像素的内边距
main_frame.pack(fill=tk.BOTH, expand=True) # 填充整个窗口并允许扩展
# 输入文本区域
self.create_input_area(main_frame)
# 处理选项区域
self.create_processing_options(main_frame)
# 输出文本区域
self.create_output_area(main_frame)
# 底部按钮区域
self.create_button_area(main_frame)
def create_input_area(self, parent):
"""创建输入文本区域"""
# 输入标签
input_label = ttk.Label(parent, text="输入文本:")
input_label.grid(row=0, column=0, sticky=tk.W, pady=(0, 5)) # 靠左对齐,底部5像素间距
# 输入文本框(带滚动条)
self.input_text = scrolledtext.ScrolledText(
parent,
wrap=tk.WORD, # 按单词换行
width=60,
height=10,
font=('Arial', 10) # 设置字体
)
self.input_text.grid(row=1, column=0, columnspan=2, sticky=tk.EW) # 跨两列,水平扩展
# 添加示例文本按钮
example_btn = ttk.Button(
parent,
text="加载示例文本",
command=self.load_example_text
)
example_btn.grid(row=2, column=0, sticky=tk.W, pady=(5, 10)) # 靠左对齐,上下间距
def create_processing_options(self, parent):
"""创建文本处理选项区域"""
# 选项框架容器
options_frame = ttk.LabelFrame(parent, text="处理选项", padding="10")
options_frame.grid(row=3, column=0, columnspan=2, sticky=tk.EW, pady=(0, 10)) # 跨两列,水平扩展
# 创建选项卡控件
self.notebook = ttk.Notebook(options_frame)
self.notebook.pack(fill=tk.BOTH, expand=True)
# 创建各个功能选项卡
self.create_replace_tab() # 字符替换
self.create_paragraph_tab() # 段落处理
self.create_position_tab() # 位置插入
self.create_space_tab() # 空格处理
self.create_regex_tab() # 正则表达式
def create_replace_tab(self):
"""创建字符替换选项卡"""
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="字符替换") # 添加到笔记本控件
# 查找字符标签和输入框
ttk.Label(tab, text="查找字符:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
self.find_entry = ttk.Entry(tab, width=30)
self.find_entry.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
# 替换为标签和输入框
ttk.Label(tab, text="替换为:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
self.replace_entry = ttk.Entry(tab, width=30)
self.replace_entry.grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)
# 是否区分大小写复选框
self.case_sensitive = tk.BooleanVar()
case_check = ttk.Checkbutton(
tab,
text="区分大小写",
variable=self.case_sensitive
)
case_check.grid(row=2, column=0, columnspan=2, sticky=tk.W, padx=5, pady=5)
def create_paragraph_tab(self):
"""创建段落处理选项卡"""
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="段落处理") # 添加到笔记本控件
# 段前插入
ttk.Label(tab, text="段前插入:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
self.prefix_entry = ttk.Entry(tab, width=30)
self.prefix_entry.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
# 段尾插入
ttk.Label(tab, text="段尾插入:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
self.suffix_entry = ttk.Entry(tab, width=30)
self.suffix_entry.grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)
# 说明标签
note = ttk.Label(tab, text="段落是以换行符分隔的文本块")
note.grid(row=2, column=0, columnspan=2, sticky=tk.W, padx=5, pady=5)
def create_position_tab(self):
"""创建位置插入选项卡"""
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="位置插入") # 添加到笔记本控件
# 插入位置
ttk.Label(tab, text="插入位置(从0开始):").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
self.position_entry = ttk.Entry(tab, width=30)
self.position_entry.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
# 插入内容
ttk.Label(tab, text="插入内容:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
self.insert_entry = ttk.Entry(tab, width=30)
self.insert_entry.grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)
# 说明标签
note = ttk.Label(tab, text="位置是基于每行文本的字符索引")
note.grid(row=2, column=0, columnspan=2, sticky=tk.W, padx=5, pady=5)
def create_space_tab(self):
"""创建空格处理选项卡"""
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="空格处理") # 添加到笔记本控件
# 空格替换选项
self.space_option = tk.StringVar(value="none") # 默认不处理
# 单选按钮
ttk.Radiobutton(
tab,
text="不处理空格",
variable=self.space_option,
value="none"
).grid(row=0, column=0, sticky=tk.W, padx=5, pady=2)
ttk.Radiobutton(
tab,
text="删除所有空格",
variable=self.space_option,
value="remove_all"
).grid(row=1, column=0, sticky=tk.W, padx=5, pady=2)
ttk.Radiobutton(
tab,
text="替换为指定字符",
variable=self.space_option,
value="replace"
).grid(row=2, column=0, sticky=tk.W, padx=5, pady=2)
# 替换字符输入框
self.space_replace_entry = ttk.Entry(tab, width=30)
self.space_replace_entry.grid(row=2, column=1, sticky=tk.W, padx=5, pady=2)
self.space_replace_entry.insert(0, "_") # 默认替换为下划线
def create_regex_tab(self):
"""创建正则表达式选项卡"""
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="正则表达式") # 添加到笔记本控件
# 正则表达式模式
ttk.Label(tab, text="正则模式:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
self.regex_pattern = ttk.Entry(tab, width=30)
self.regex_pattern.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
# 替换内容
ttk.Label(tab, text="替换内容:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
self.regex_replace = ttk.Entry(tab, width=30)
self.regex_replace.grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)
# 说明标签
note = ttk.Label(tab, text="使用Python re模块语法,如\\d匹配数字")
note.grid(row=2, column=0, columnspan=2, sticky=tk.W, padx=5, pady=5)
def create_output_area(self, parent):
"""创建输出文本区域"""
# 输出标签
output_label = ttk.Label(parent, text="输出文本:")
output_label.grid(row=4, column=0, sticky=tk.W, pady=(0, 5)) # 靠左对齐,底部5像素间距
# 输出文本框(带滚动条)
self.output_text = scrolledtext.ScrolledText(
parent,
wrap=tk.WORD, # 按单词换行
width=60,
height=10,
font=('Arial', 10), # 设置字体
state='disabled' # 初始状态为禁用
)
self.output_text.grid(row=5, column=0, columnspan=2, sticky=tk.EW) # 跨两列,水平扩展
def create_button_area(self, parent):
"""创建底部按钮区域"""
# 按钮框架
button_frame = ttk.Frame(parent)
button_frame.grid(row=6, column=0, columnspan=2, pady=(10, 0)) # 跨两列,顶部10像素间距
# 处理按钮
process_btn = ttk.Button(
button_frame,
text="处理文本",
command=self.process_text
)
process_btn.pack(side=tk.LEFT, padx=5) # 靠左放置,左右5像素间距
# 清除按钮
clear_btn = ttk.Button(
button_frame,
text="清除所有",
command=self.clear_all
)
clear_btn.pack(side=tk.LEFT, padx=5) # 靠左放置,左右5像素间距
# 复制按钮
copy_btn = ttk.Button(
button_frame,
text="复制结果",
command=self.copy_result
)
copy_btn.pack(side=tk.LEFT, padx=5) # 靠左放置,左右5像素间距
def load_example_text(self):
"""加载示例文本到输入框"""
example_text = """这是一个示例文本。
你可以在这里测试各种文本处理功能。
第二段落 包含多个空格。
第三段落: 数字123, 字母abc, 特殊字符!@#。
最后一段落。"""
self.input_text.delete(1.0, tk.END) # 清空输入框
self.input_text.insert(tk.END, example_text) # 插入示例文本
def process_text(self):
"""处理文本并显示结果"""
# 获取输入文本
input_text = self.input_text.get(1.0, tk.END)
if not input_text.strip():
messagebox.showwarning("警告", "请输入要处理的文本!")
return
# 初始化处理结果
processed_text = input_text
try:
# 获取当前选中的选项卡
current_tab = self.notebook.tab(self.notebook.select(), "text")
# 根据不同的选项卡执行不同的处理
if current_tab == "字符替换":
processed_text = self.process_replace(processed_text)
elif current_tab == "段落处理":
processed_text = self.process_paragraph(processed_text)
elif current_tab == "位置插入":
processed_text = self.process_position(processed_text)
elif current_tab == "空格处理":
processed_text = self.process_spaces(processed_text)
elif current_tab == "正则表达式":
processed_text = self.process_regex(processed_text)
# 显示处理结果
self.display_result(processed_text)
except Exception as e:
messagebox.showerror("错误", f"处理文本时出错:\n{str(e)}")
def process_replace(self, text):
"""执行字符替换处理"""
find_str = self.find_entry.get()
replace_str = self.replace_entry.get()
case_sensitive = self.case_sensitive.get()
if not find_str:
return text # 如果没有查找字符串,直接返回原文本
# 根据是否区分大小写进行替换
if case_sensitive:
return text.replace(find_str, replace_str)
else:
# 不区分大小写替换
return re.sub(re.escape(find_str), replace_str, text, flags=re.IGNORECASE)
def process_paragraph(self, text):
"""执行段落处理"""
prefix = self.prefix_entry.get()
suffix = self.suffix_entry.get()
# 分割段落(按换行符)
paragraphs = text.split('\n')
# 处理每个段落
processed_paragraphs = []
for para in paragraphs:
processed_para = prefix + para + suffix
processed_paragraphs.append(processed_para)
# 重新组合段落
return '\n'.join(processed_paragraphs)
def process_position(self, text):
"""执行位置插入处理"""
try:
position = int(self.position_entry.get())
except ValueError:
messagebox.showerror("错误", "位置必须是整数!")
return text
insert_str = self.insert_entry.get()
# 分割行
lines = text.split('\n')
# 处理每行
processed_lines = []
for line in lines:
if position <= len(line):
# 在指定位置插入
processed_line = line[:position] + insert_str + line[position:]
else:
# 如果位置超出范围,直接使用原行
processed_line = line
processed_lines.append(processed_line)
# 重新组合行
return '\n'.join(processed_lines)
def process_spaces(self, text):
"""执行空格处理"""
option = self.space_option.get()
if option == "none":
return text # 不处理
elif option == "remove_all":
# 删除所有空格(包括制表符等空白字符)
return re.sub(r'\s+', '', text)
elif option == "replace":
# 替换为指定字符
replace_char = self.space_replace_entry.get()
return re.sub(r'\s', replace_char, text)
def process_regex(self, text):
"""执行正则表达式替换"""
pattern = self.regex_pattern.get()
replace_str = self.regex_replace.get()
if not pattern:
return text # 如果没有正则模式,直接返回原文本
try:
# 尝试编译正则表达式以验证其有效性
re.compile(pattern)
# 执行替换
return re.sub(pattern, replace_str, text)
except re.error as e:
messagebox.showerror("正则表达式错误", f"无效的正则表达式:\n{str(e)}")
return text
def display_result(self, text):
"""在输出框中显示处理结果"""
self.output_text.config(state='normal') # 启用编辑
self.output_text.delete(1.0, tk.END) # 清空输出框
self.output_text.insert(tk.END, text) # 插入处理后的文本
self.output_text.config(state='disabled') # 禁用编辑
def clear_all(self):
"""清除所有输入和输出"""
# 清空输入框
self.input_text.delete(1.0, tk.END)
# 清空输出框
self.output_text.config(state='normal')
self.output_text.delete(1.0, tk.END)
self.output_text.config(state='disabled')
# 重置所有输入字段
self.find_entry.delete(0, tk.END)
self.replace_entry.delete(0, tk.END)
self.case_sensitive.set(False)
self.prefix_entry.delete(0, tk.END)
self.suffix_entry.delete(0, tk.END)
self.position_entry.delete(0, tk.END)
self.insert_entry.delete(0, tk.END)
self.space_option.set("none")
self.space_replace_entry.delete(0, tk.END)
self.space_replace_entry.insert(0, "_")
self.regex_pattern.delete(0, tk.END)
self.regex_replace.delete(0, tk.END)
def copy_result(self):
"""复制输出结果到剪贴板"""
result = self.output_text.get(1.0, tk.END)
if result.strip():
self.root.clipboard_clear() # 清空剪贴板
self.root.clipboard_append(result) # 添加内容到剪贴板
messagebox.showinfo("成功", "结果已复制到剪贴板!")
else:
messagebox.showwarning("警告", "没有可复制的内容!")
if __name__ == "__main__":
# 创建主窗口并运行应用程序
root = tk.Tk()
app = TextProcessorApp(root)
root.mainloop()
软件功能说明
这个文本处理软件使用Python的Tkinter库实现,采用面向对象编程方式,具有以下功能:
-
字符替换功能:
- 查找并替换指定字符
- 可选是否区分大小写
-
段落处理功能:
- 在每段开头插入指定字符
- 在每段结尾插入指定字符
-
位置插入功能:
- 在每行指定位置插入指定字符
- 位置从0开始计数
-
空格处理功能:
- 删除所有空格
- 将空格替换为指定字符
- 保留原样不处理
-
正则表达式替换:
- 使用Python re模块语法
- 支持复杂的模式匹配和替换
-
其他功能:
- 加载示例文本
- 清除所有输入
- 复制处理结果到剪贴板
代码特点
- 面向对象设计:所有功能封装在TextProcessorApp类中
- 模块化结构:每个功能区域有独立的创建方法
- 详细注释:每行代码都有解释其功能的注释
- 错误处理:对用户输入进行验证和错误提示
- 用户友好:清晰的界面布局和操作提示
使用方法
- 在输入框中输入或粘贴要处理的文本(或点击"加载示例文本")
- 选择需要的处理功能选项卡
- 设置相应的处理参数
- 点击"处理文本"按钮查看结果
- 可以使用"复制结果"按钮复制处理后的文本