Python文件字符统计与用户管理系统
一、统计文件中所有字符及其出现次数(不区分大小写)
任务要求统计一个文本文件中每个字符的出现次数,忽略大小写,并将标点符号和空格也包含在内。
# 统计文件中的字符频率
from collections import defaultdict
result_dict = defaultdict(int)
with open('data.txt', 'r', encoding='utf-8') as file:
content = file.read().lower()
for char in content:
result_dict[char] += 1
print(dict(result_dict))
二、统计文件中大写字母、小写字母、数字及其他字符的数量
此任务需要对文件内容进行分类统计,包括大写字母、小写字母、数字和其他字符。
stats = {'大写字母': 0, '小写字母': 0, '数字': 0, '其他字符': 0}
with open('data2.txt', 'r', encoding='utf-8') as file:
content = file.read()
for char in content:
if char.isupper():
stats['大写字母'] += 1
elif char.islower():
stats['小写字母'] += 1
elif char.isdigit():
stats['数字'] += 1
else:
stats['其他字符'] += 1
print(stats)
三、用户登录注册系统
设计一个简单的用户管理系统,支持用户注册、登录功能,并具备错误处理和数据持久化能力。
import time
USER_DB = 'users.txt'
BLACKLIST_DB = 'blacklist.txt'
def load_users():
users = {}
with open(USER_DB, 'r', encoding='utf-8') as f:
for line in f:
username, password, remark = line.strip().split('|')
users[username] = {'password': password, 'remark': remark}
return users
def save_user(username, password, remark):
with open(USER_DB, 'a', encoding='utf-8') as f:
f.write(f"{username}|{password}|{remark}\n")
def blacklist_user(username):
with open(BLACKLIST_DB, 'a', encoding='utf-8') as f:
f.write(f"{username}\n")
def is_blacklisted(username):
with open(BLACKLIST_DB, 'r', encoding='utf-8') as f:
return username in [line.strip() for line in f]
def register():
while True:
username = input("请输入用户名:")
password = input("请输入密码:")
confirm_password = input("请再次输入密码:")
remark = input("请输入备注信息(可选):") or "无"
if password != confirm_password:
print("两次输入的密码不一致,请重新尝试!")
continue
users = load_users()
if username in users:
print("该用户名已存在,请选择其他用户名!")
else:
save_user(username, password, remark)
print("注册成功!")
break
def login():
attempts = 0
max_attempts = 3
while attempts < max_attempts:
username = input("请输入用户名:")
password = input("请输入密码:")
if is_blacklisted(username):
print("该用户已被锁定,请联系管理员!")
return
users = load_users()
if username in users and users[username]['password'] == password:
print("登录成功!")
return
else:
attempts += 1
print(f"用户名或密码错误,您还有 {max_attempts - attempts} 次机会!")
if attempts >= max_attempts:
print("多次登录失败,账户已被锁定!")
blacklist_user(username)
def main():
while True:
print("\n1. 注册\n2. 登录\n0. 退出")
choice = input("请选择操作:")
if choice == '1':
register()
elif choice == '2':
login()
elif choice == '0':
print("感谢使用,再见!")
break
else:
print("无效选项,请重试!")
if __name__ == '__main__':
main()