Python项目实践:控制台银行系统与词频统计工具开发指南
引言
Python以其简洁优雅的语法和强大的功能库,成为最受欢迎的编程语言之一。本文将带你实战两个经典的Python项目:控制台版银行系统和词频统计工具。这些项目不仅能巩固Python基础,还能让你掌握文件操作、数据处理等实用技能,特别适合Python初学者和希望提升实战能力的开发者。
一、控制台版银行系统开发
1. 系统功能设计
这个银行系统将实现以下核心功能:
-
账户开户
-
账户登录
-
存款操作
-
取款操作
-
转账功能
-
查询余额
-
交易记录查询
2. 项目架构设计
bank_system/
├── main.py # 程序入口
├── accounts/ # 账户数据存储目录
├── transactions/ # 交易记录存储目录
├── utils.py # 工具函数
└── bank_operations.py # 银行业务逻辑
3. 核心代码实现
银行业务逻辑(bank_operations.py)
import os
import json
from datetime import datetimeclass BankAccount:def __init__(self, account_number, password, name, initial_balance=0):self.account_number = account_numberself.password = passwordself.name = nameself.balance = initial_balanceself.transactions = []def deposit(self, amount):if amount <= 0:return False, "存款金额必须大于0"self.balance += amountself._record_transaction("存款", amount)return True, f"存款成功,当前余额: {self.balance}"def withdraw(self, amount):if amount <= 0:return False, "取款金额必须大于0"if amount > self.balance:return False, "余额不足"self.balance -= amountself._record_transaction("取款", amount)return True, f"取款成功,当前余额: {self.balance}"def transfer(self, target_account, amount):if amount <= 0:return False, "转账金额必须大于0"if amount > self.balance:return False, "余额不足"self.balance -= amounttarget_account.balance += amountself._record_transaction(f"转账至{target_account.account_number}", amount)target_account._record_transaction(f"来自{self.account_number}的转账", amount)return True, f"转账成功,当前余额: {self.balance}"def _record_transaction(self, transaction_type, amount):transaction = {"type": transaction_type,"amount": amount,"balance": self.balance,"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}self.transactions.append(transaction)self._save_transaction(transaction)def _save_transaction(self, transaction):transaction_file = f"transactions/{self.account_number}.json"with open(transaction_file, "a") as f:f.write(json.dumps(transaction) + "\n")def save_account(self):account_data = {"account_number": self.account_number,"password": self.password,"name": self.name,"balance": self.balance}account_file = f"accounts/{self.account_number}.json"with open(account_file, "w") as f:json.dump(account_data, f)@classmethoddef load_account(cls, account_number):account_file = f"accounts/{account_number}.json"if not os.path.exists(account_file):return Nonewith open(account_file) as f:account_data = json.load(f)account = cls(account_data["account_number"],account_data["password"],account_data["name"],account_data["balance"])return account
主程序(main.py)
from bank_operations import BankAccount
import os
import randomdef clear_screen():os.system('cls' if os.name == 'nt' else 'clear')def create_account():clear_screen()print("\n----- 开户 -----")name = input("请输入您的姓名: ")password = input("设置账户密码: ")account_number = str(random.randint(100000, 999999))initial_balance = float(input("请输入初始存款金额: "))account = BankAccount(account_number, password, name, initial_balance)account.save_account()print(f"\n开户成功! 您的账户信息如下:")print(f"账户号码: {account_number}")print(f"账户姓名: {name}")print(f"初始余额: {initial_balance}")input("\n按任意键返回主菜单...")def login():clear_screen()print("\n----- 登录 -----")account_number = input("请输入账户号码: ")password = input("请输入密码: ")account = BankAccount.load_account(account_number)if not account or account.password != password:print("账户号码或密码错误!")input("\n按任意键返回...")return Nonereturn accountdef account_menu(account):while True:clear_screen()print(f"\n----- 欢迎, {account.name} -----")print(f"账户余额: {account.balance}")print("1. 存款")print("2. 取款")print("3. 转账")print("4. 查询交易记录")print("0. 退出登录")choice = input("请选择操作: ")if choice == "1":amount = float(input("请输入存款金额: "))success, message = account.deposit(amount)print(message)account.save_account()input("\n按任意键继续...")elif choice == "2":amount = float(input("请输入取款金额: "))success, message = account.withdraw(amount)print(message)if success:account.save_account()input("\n按任意键继续...")elif choice == "3":target_number = input("请输入对方账户号码: ")target_account = BankAccount.load_account(target_number)if not target_account:print("目标账户不存在!")else:amount = float(input("请输入转账金额: "))success, message = account.transfer(target_account, amount)print(message)if success:account.save_account()target_account.save_account()input("\n按任意键继续...")elif choice == "4":print("\n----- 交易记录 -----")for trans in account.transactions:print(f"{trans['time']} - {trans['type']}: {trans['amount']}, 余额: {trans['balance']}")input("\n按任意键继续...")elif choice == "0":breakelse:print("无效选择!")input("\n按任意键继续...")def main():# 创建必要的目录os.makedirs("accounts", exist_ok=True)os.makedirs("transactions", exist_ok=True)while True:clear_screen()print("\n===== 银行系统 =====")print("1. 开户")print("2. 登录")print("0. 退出系统")choice = input("请选择操作: ")if choice == "1":create_account()elif choice == "2":account = login()if account:account_menu(account)elif choice == "0":print("感谢使用银行系统,再见!")breakelse:print("无效选择!")input("\n按任意键继续...")if __name__ == "__main__":main()
4. 项目优化方向
-
加密存储:对密码和敏感信息进行加密
-
账户锁定:添加密码错误次数限制
-
数据验证:增强输入数据的验证
-
利率计算:添加定期存款和利息计算功能
-
图形界面:使用Tkinter或PyQt开发GUI界面
二、词频统计工具开发
1. 工具功能设计
-
读取文本文件(.txt)
-
统计单词出现频率
-
支持自定义停用词过滤
-
按词频排序输出
-
结果保存为CSV文件
2. 核心代码实现
import re
import csv
from collections import defaultdictclass WordFrequencyAnalyzer:def __init__(self, stop_words=None):self.stop_words = set(stop_words) if stop_words else set()def clean_text(self, text):# 转换为小写并移除非字母字符text = text.lower()text = re.sub(r'[^a-zA-Z\s]', '', text)return textdef get_word_frequency(self, file_path):word_counts = defaultdict(int)try:with open(file_path, 'r', encoding='utf-8') as file:for line in file:cleaned_line = self.clean_text(line)words = cleaned_line.split()for word in words:if word not in self.stop_words:word_counts[word] += 1except FileNotFoundError:print(f"错误: 文件 {file_path} 未找到!")return Noneexcept Exception as e:print(f"读取文件时发生错误: {e}")return Nonereturn word_countsdef save_results(self, word_counts, output_file):sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)try:with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:writer = csv.writer(csvfile)writer.writerow(['单词', '出现次数'])for word, count in sorted_words:writer.writerow([word, count])print(f"结果已保存到 {output_file}")except Exception as e:print(f"保存结果时发生错误: {e}")def print_top_words(self, word_counts, top_n=10):sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)print("\nTop {} 高频单词:".format(top_n))print("{:<15} {:<10}".format('单词', '出现次数'))print("-" * 25)for word, count in sorted_words[:top_n]:print("{:<15} {:<10}".format(word, count))def main():print("===== 词频统计工具 =====")file_path = input("请输入要分析的文本文件路径: ")# 可自定义停用词列表custom_stop_words = input("请输入要排除的停用词(用逗号分隔,直接回车跳过): ")stop_words = [w.strip() for w in custom_stop_words.split(',')] if custom_stop_words else Noneanalyzer = WordFrequencyAnalyzer(stop_words)word_counts = analyzer.get_word_frequency(file_path)if word_counts:analyzer.print_top_words(word_counts)save_option = input("\n是否保存结果到CSV文件? (y/n): ").lower()if save_option == 'y':output_file = input("请输入输出文件名(默认: word_frequency.csv): ") or "word_frequency.csv"analyzer.save_results(word_counts, output_file)if __name__ == "__main__":main()
3. 工具扩展功能
-
多文件处理:支持批量处理多个文本文件
-
词云生成:使用wordcloud库可视化结果
-
NLP分析:添加情感分析或主题提取功能
-
GUI界面:开发图形用户界面更易使用
-
数据库支持:将结果存储到数据库便于长期分析
4. 使用示例
假设我们有一个sample.txt
文件,内容如下:
Python is a great language. Python is easy to learn and powerful.
Python can be used for web development, data analysis, AI and more.
Python, python, PYTHON!
运行词频统计工具后的输出:
===== 词频统计工具 =====
请输入要分析的文本文件路径: sample.txt
请输入要排除的停用词(用逗号分隔,直接回车跳过): be,to,and,for,canTop 10 高频单词:
单词 出现次数
-------------------------
python 4
is 2
great 1
language 1
easy 1
learn 1
powerful 1
used 1
web 1
development 1是否保存结果到CSV文件? (y/n): y
请输入输出文件名(默认: word_frequency.csv):
结果已保存到 word_frequency.csv
三、项目实践的价值
通过这两个Python项目的开发,你将掌握:
-
文件操作:读写文本文件、JSON和CSV
-
数据处理:字符串处理、正则表达式
-
面向对象:类的设计与封装
-
数据结构:字典、集合的灵活运用
-
异常处理:编写健壮的代码
-
模块化开发:合理的代码组织
四、学习建议
-
逐步迭代:先实现核心功能,再逐步添加特性
-
代码重构:功能完成后优化代码结构和性能
-
文档规范:为函数和类添加docstring
-
单元测试:编写测试用例确保代码质量
-
版本控制:使用Git管理项目版本
结语
这两个Python项目涵盖了从基础语法到实际应用的多个方面,是巩固Python技能的绝佳实践。建议你在完成基础版本后,尝试实现文中提到的扩展功能,这将大大提升你的编程能力。
欢迎在评论区分享你的实现代码或遇到的问题,我们一起交流进步!