这是的第一次用代码去实现一些生活中的问题,第一次体会到编程技能的实用性
这是一个用Python写的小程序,主要目的就是为了实现将文本中的单词乱序后分组输出,适合个人制定背单词计划
文章目录
- 程序流程分析
- 一、准备工作
- 二、代码实现
- 1.做一个界面
- 2.读入文件
- 3.乱序实现
- 4.分组输出
- 5.程序打包
- 完成品
- 三、总结
程序流程分析
就是一个简单的python写的小程序,目的就是正序输入,乱序分组输出,最后打包成exe
(我是新手,所以目前很菜,,我会努力变强的(应该?))
一、准备工作
要实现目的,需要准备的库:
随机程序,random库;
文件读取操作,os库(但是好像没用上)
迭代操作,itertools
图形界面设计,tkinter库;
文件处理操作,tkinter的filedialog库;
消息弹窗,tkinter的messagebox
引入库
(tkinter库需要提前安装)
import random
import tkinter as tk
import itertools
import os
from tkinter import filedialog
from tkinter import messagebox
二、代码实现
1.做一个界面
代码如下:
class WordStirrerApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("单词搅拌器")
self.geometry("400x300+730+200") # 调整窗口大小和位置
self.label_intro = tk.Label(self, text="这是一个单词搅拌器,选择一个txt文件\ntxt文件要求:每行只有一个单词\n会输出一个乱序的单词文件分组保存到本程序目录下")
self.label_intro.pack(padx=5, pady=5)
self.label_filepath = tk.Label(self, text="选择文件:")
self.label_filepath.pack(padx=5, pady=5)
self.entry_filepath = tk.Entry(self, width=50) # 增加输入框宽度
self.entry_filepath.pack(padx=5, pady=5)
self.button_browse = tk.Button(self, text="浏览", command=self.browse_file)
self.button_browse.pack(padx=5, pady=5)
self.label_quantity = tk.Label(self, text="每组数量:")
self.label_quantity.pack(padx=5, pady=5)
self.entry_quantity = tk.Entry(self)
self.entry_quantity.pack(padx=5, pady=5)
self.button_start = tk.Button(self, text="开始搅拌", command=self.start_stirring)
self.button_start.pack(padx=5, pady=20) # 增加按钮下方的空白
def browse_file(self):
# 使用文件对话框让用户选择文件
filepath = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
self.entry_filepath.delete(0, tk.END) # 清空输入框
self.entry_filepath.insert(0, filepath) # 插入选择的文件路径
def start_stirring(self):
# 获取用户输入的文件路径和每组数量
filepath = self.entry_filepath.get()
quantity = self.entry_quantity.get()
if __name__ == "__main__": #显示出界面
app = WordStirrerApp()
app.mainloop()
这就是一个单纯的界面(我太菜了,下面是某GPT的解读)
- 类定义:这行代码定义了一个名为 WordStirrerApp 的类,它继承自 tkinter 模块中的 Tk 类,这是创建根窗口的类。
class WordStirrerApp(tk.Tk):
- 初始化方法:
初始化方法 __init__ 是类的构造函数,它首先调用父类的构造函数 super().__init__() 来创建窗口。然后,它设置窗口的标题、大小和位置,并创建一系列的 Label、Entry 和 Button 组件来构建用户界面。
界面组件:
* Label 组件用于显示文本信息,如程序介绍、文件路径标签和每组数量标签。
* Entry 组件用于获取用户输入,一个是文件路径输入框,另一个是每组数量输入框。
* Button 组件用于触发操作,一个是浏览按钮,用于打开文件对话框选择文件;另一个是开始搅拌按钮,用于启动单词搅拌过程。
事件处理方法:
browse_file 方法用于打开文件对话框,让用户选择一个文本文件。选择的文件路径将被插入到文件路径输入框中。
start_stirring 方法是开始搅拌按钮的事件处理函数。它获取用户输入的文件路径和每组数量,但目前这个方法只包含了获取输入的部分,没有实现单词搅拌的逻辑。
(详情见成品)def __init__(self): super().__init__() # ... 界面布局和组件定义 ...
- 程序入口:这段代码是程序的入口点。当这个脚本被直接运行时(而不是被导入到另一个脚本中),它会创建 WordStirrerApp 类的实例并启动主事件循环,这样用户界面就会显示出来,并且可以响应用户的交互。
if __name__ == "__main__": app = WordStirrerApp() app.mainloop()
2.读入数据
# 读取文件并打乱单词
with open(filepath, "r", encoding="utf-8") as file: # 指定编码为utf-8
lines = file.readlines()
# 移除空行和空白字符
lines = [line.strip() for line in lines if line.strip()]
指定路径打开,按行读取文件
(这就是这个程序的局限性了,因为word和PDF格式相对复杂,我就没搞)
(按行读取也是限制了这个程序,对输入文件有着很高的要求)
if not filepath or not quantity:
messagebox.showerror("错误", "请选择文件并输入每组数量。")
return
try:
quantity = int(quantity)
except ValueError:
messagebox.showerror("错误", "请输入一个有效的数字作为每组数量。")
return
程序优化,清空原有框中内容,加入错输报错提示
3.乱序实现
random.shuffle(lines)
random.shuffle() 函数随机打乱列表 lines 中的元素顺序,这样文件中的单词就会以随机顺序排列。
4.分组输出
# 将单词分组并写入新文件
for i, chunk in enumerate(grouper(lines, quantity), start=1):
output_filepath = f"搅拌成果_第{i}天的.txt"
with open(output_filepath, 'w', encoding="utf-8") as output_file:
for line in chunk:
output_file.write(line + '\n')
提示弹窗:
messagebox.showinfo("搅拌结果", "成功了,回到该程序所在目录查看结果。")
5.程序打包
- 安装PyInstaller: 如果你还没有安装PyInstaller,你可以通过pip来安装它
pip install pyinstaller
- 打包程序: 打开命令提示符或终端,导航到你的Python脚本所在的目录,然后运行以下命令:
pyinstaller --onefile your_script.py
其中your_script.py是你的Python脚本的名字。--onefile参数告诉PyInstaller将程序打包成一个单一的.exe文件。
(可以找朋友调试一下,看看有没有问题。。)
完成品
import tkinter as tk
from tkinter import filedialog
import random
import itertools
import os
from tkinter import messagebox
class WordStirrerApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("单词搅拌器")
self.geometry("400x300+730+200") # 调整窗口大小和位置
self.label_intro = tk.Label(self, text="这是一个单词搅拌器,选择一个txt文件\ntxt文件要求:每行只有一个单词\n会输出一个乱序的单词文件分组保存到本程序目录下")
self.label_intro.pack(padx=5, pady=5)
self.label_filepath = tk.Label(self, text="选择文件:")
self.label_filepath.pack(padx=5, pady=5)
self.entry_filepath = tk.Entry(self, width=50) # 增加输入框宽度
self.entry_filepath.pack(padx=5, pady=5)
self.button_browse = tk.Button(self, text="浏览", command=self.browse_file)
self.button_browse.pack(padx=5, pady=5)
self.label_quantity = tk.Label(self, text="每组数量:")
self.label_quantity.pack(padx=5, pady=5)
self.entry_quantity = tk.Entry(self)
self.entry_quantity.pack(padx=5, pady=5)
self.button_start = tk.Button(self, text="开始搅拌", command=self.start_stirring)
self.button_start.pack(padx=5, pady=20) # 增加按钮下方的空白
def browse_file(self):
# 使用文件对话框让用户选择文件
filepath = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
self.entry_filepath.delete(0, tk.END) # 清空输入框
self.entry_filepath.insert(0, filepath) # 插入选择的文件路径
def start_stirring(self):
# 获取用户输入的文件路径和每组数量
filepath = self.entry_filepath.get()
quantity = self.entry_quantity.get()
if not filepath or not quantity:
messagebox.showerror("错误", "请选择文件并输入每组数量。")
return
try:
quantity = int(quantity)
except ValueError:
messagebox.showerror("错误", "请输入一个有效的数字作为每组数量。")
return
# 读取文件并打乱单词
with open(filepath, "r", encoding="utf-8") as file: # 指定编码为utf-8
lines = file.readlines()
random.shuffle(lines)
# 移除空行和空白字符
lines = [line.strip() for line in lines if line.strip()]
# 将单词分组并写入新文件
for i, chunk in enumerate(grouper(lines, quantity), start=1):
output_filepath = f"搅拌成果_第{i}天的.txt"
with open(output_filepath, 'w', encoding="utf-8") as output_file:
#output_file.writelines(chunk)
for line in chunk:
output_file.write(line + '\n')
messagebox.showinfo("搅拌结果", "成功了,回到该程序所在目录查看结果。")
def grouper(iterable, n):
# 分块迭代器,将可迭代对象分割成指定大小的块
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue='')
if __name__ == "__main__":
app = WordStirrerApp()
app.mainloop()
总结
- 下次再也不敢拖延了,拖了好久,我都要忘了我写的什么东西了(×)
- 别学边做的东西,借助了一些GPT的力量(AI是真的太强大了!)
- 第一次,把自己心中的想法做出了,感觉很棒(说实话是为了帮一个朋友减轻工作压力)
- Python需要学的东西还有很多,继续加油!!
最爱富岗义勇