Python入门,领略函数式编程的魅力!!(小白可食用)

python入门
仅限新手,一个简单的博客系统,理解函数式编程的魅力。
本文用的IDE为pytchram 2018.3
仅限编程小白食用,人生苦短,我用Python。

模拟简单的博客

1.账号注册,登陆验证

2.写文章,包含【标题,作者,时间,内容】

3.查询文章,列出所有文章及时间

4.可查看其中一篇文章

5.删除文章

6.修改文章

7.退出系统

import os,json,time,sys
from datetime import datetime

#功能->1.账号注册,登陆验证

#【确定好】 用户表的结构!!

userTable={“users”:[{“name”:“admin”,“pwd”:“123456”}]}

userTable[“users”].append({“name”:“张三”,“pwd”:“789456”})

print(userTable)

1.读取用户配置表 : 配置表存在 返回读取结果,不存在 创建配置表!

def ReadAllUser(path=“user.json”):
if os.path.exists(path): #路径存在!
with open(path) as f_r:
return json.load(f_r)
else:
with open(path,“w”) as f_w:
userTable = {“users”: [{“name”: “admin”, “pwd”: “123456”}]}
json.dump(userTable,f_w)
print(“创建默认配置表成功!”)
return userTable #返回默认值!

x=ReadAllUser()

print(x,type(x))

2.写入用户配置表 :将用户表更新 ,将全部 覆盖写入!

def UpdateUser(userDict,path=“user.json”):
with open(path,“w”) as f_w:
json.dump(userDict,f_w)
print(“更新成功!”)

默认文章1.【创建默认的用户文章表】!!! 【注册成功 调用!!!】

def CreateDefaultArticle(name,path=“Article”):
if os.path.exists(path):
with open(os.path.join(path,name+".json"),“w”) as f_w:
#默认的文章表
articleTable={“article”:[
{“title”:“default title”,
“author”:name,
“date”:datetime.now().strftime("%Y{}%m{}%d{} %H:%M:%S").format(“年”,“月”,“日”),
“content”:“default content”
},
]}
json.dump(articleTable,f_w)
print(“已创建默认 文章!”)
else:
os.mkdir(path)
with open(os.path.join(path, name + “.json”), “w”) as f_w:
# 默认的文章表
articleTable = {“article”: [
{“title”: “default title”,
“author”: name,
“date”: datetime.now().strftime("%Y{}%m{}%d{} %H:%M:%S").format(“年”, “月”, “日”),
“content”: “default content”
},
]}
json.dump(articleTable, f_w)
print(“已创建默认 文章!”)

3.注册 : 用户不存在-可以注册, 用户存在-注册失败

def Register(path=“user.json”):
while True:
print(“开始注册”.center(50,"*"))
#1.用户输入
name=input(“请输入注册用户名?”)
pwd=input(“请输入%s的密码?”%(name))

    #2.判读用户名是否重复!!!
    temp=ReadAllUser(path) #读取所有!

    isFind=False # False 不存在,
    for i in temp["users"]:
        if i["name"]==name:
            print("用户名已存在,注册失败!")
            isFind=True
            break
    #3.不存在 注册成功!
    if isFind==False:
        #注册
        curUser={"name":name,"pwd":pwd}
        temp["users"].append(curUser)
        #更新
        UpdateUser(temp,path)
        print("注册成功!")
        #产生默认文章!
        CreateDefaultArticle(name)
        return True #注册成功!

x=Register()

print(x)

4.登录 : 用户存在密码对->登录成功! 用户或密码错误,登录失败!

def Login(path=“user.json”):
global currentUser #内部要修改外部全局变量!!!
while True:
# 1.用户输入
name = input(“请输入用户名?”)
pwd = input(“请输入%s的密码?” % (name))

    # 2.判读用户名是否存在!!!
    temp = ReadAllUser(path)  # 读取所有!

    # 3.判断 用户和密码
    isFind=False # False 不存在
    for i in temp["users"]:
        if i["name"]==name and i["pwd"]==pwd:
            print("登录成功!")
            #更新全局用户名变量
            currentUser=name
            isFind=True
            return isFind
    if isFind==False:
        print("用户名或密码错误!重新登录!")

x=Login()

print(x)

2.写文章,包含【标题,作者,时间,内容】

【确定文章表数据结构】

#字符串时间!

x=datetime.now().strftime("%Y{}%m{}%d{} %H:%M:%S").format(“年”,“月”,“日”)

print(x,type(x))

articleTable={“article”:[

{“title”:“default title”,

“author”:“admin”,

“date”:datetime.now().strftime("%Y{}%m{}%d{} %H:%M:%S").format(“年”,“月”,“日”),

“content”:“default content”

},

{}

]}

#print(articleTable)

2.读取 文章

def ReadArticle(name,path=“Article”):
with open(os.path.join(path,name+".json")) as f_r:
return json.load(f_r)

x=ReadArticle(“张三”)

print(x)

2.1写入文章表

def UpdateArticle(name,allArticle,path=“Article”):
with open(os.path.join(path,name+".json"),“w”) as f_w:
json.dump(allArticle,f_w)
print(“更新成功!”)

3.写文章

def WriteArticle(name,path=“Article”):
print(“开始写文章!”.center(50,"*"))
title=input(“请输入标题–》?”)
content=input(“请输入内容–》?”)
#临时文章dict
temp= {
“title”:title,
“author”:name,
“date”:datetime.now().strftime("%Y{}%m{}%d{} %H:%M:%S").format(“年”,“月”,“日”),
“content”:content
}
#读取所有文章
allArticle=ReadArticle(name,path)
allArticle[“article”].append(temp)

#更新
UpdateArticle(name,allArticle,path)

WriteArticle(“张三”)

3.查询文章,列出所有文章及时间

def FindAll(name,path=“Article”):
#读取所有的文章
all=ReadArticle(name,path)
for i in range(len(all[“article”])):
print(i+1,“标题:%s,时间:%s”%(all[“article”][i][“title”],all[“article”][i][“date”]))

FindAll(“张三”)

4.可查看其中一篇文章

def FindOneArticle(name,path=“Article”):
#读取所有的文章
all=ReadArticle(name,path)
for i in range(len(all[“article”])):
print(i+1,“标题:%s,时间:%s”%(all[“article”][i][“title”],all[“article”][i][“date”]))

index=int(input("请输入您要查看的文章!"))

print("\t标题:",all["article"][index-1]["title"])
print("\t作者:",all["article"][index-1]["author"])
print("\t时间:",all["article"][index - 1]["date"])
print("\t内容:",all["article"][index - 1]["content"])

FindOneArticle(“张三”)

5.删除文章

def DeleteOneArticle(name,path=“Article”):
#读取所有的文章
all=ReadArticle(name,path)
for i in range(len(all[“article”])):
print(i+1,“标题:%s,时间:%s”%(all[“article”][i][“title”],all[“article”][i][“date”]))
if len(all[“article”])!=0:
index=int(input(“请输入您要删除的文章!”))

    all["article"].pop(index-1)
    #更新
    UpdateArticle(name,all,path)
    print("删除成功!")
else:
    print("没有文章!无法删除")

DeleteOneArticle(“张三”)

6.修改文章

def EditOneArticle(name,path=“Article”):
#读取所有的文章
all=ReadArticle(name,path)
for i in range(len(all[“article”])):
print(i+1,“标题:%s,时间:%s”%(all[“article”][i][“title”],all[“article”][i][“date”]))
if len(all[“article”])!=0:
index=int(input(“请输入您要修改的文章!”))

    print("开始修改文章!".center(50, "*"))
    title = input("请输入修改的标题--》?")
    content = input("请输入修改的内容--》?")
    # 临时文章dict
    temp = {
        "title": title,
        "author": name,
        "date": datetime.now().strftime("%Y{}%m{}%d{} %H:%M:%S").format("年", "月", "日"),
        "content": content
    }

    all["article"][index-1]=temp #更改 字典集合

    #更新
    UpdateArticle(name,all,path)
    print("修改成功!")
else:
    print("没有文章!无法修改")

EditOneArticle(“张三”)

#美丽的分割线*****

主函数

#全局变量
currentUser=""
def Main():

global  currentUser
#1. 欢迎语句
print("欢迎来到XXX皇家豪华博客系统!")
while True:
    #2. 注册  登录  退出
    selectA=input("1. 注册  2. 登录  3. 退出".center(50,"*")+("\n"+"请选择>>>".rjust(15,"*")))
    if selectA=="1":
        #注册
        Register()
    elif selectA=="2":
        #登录
        if Login():
            while True:
                selectB=input("1. 写文章  2. 查看所有  3. 查看一篇  4. 删除  5. 修改一篇  6. 退出登录".center(50,"*")+("\n"+"请选择>>>".rjust(15,"*")))
                if selectB=="1":
                    WriteArticle(currentUser)
                elif selectB=="2":
                    FindAll(currentUser)
                elif selectB=="3":
                    FindOneArticle(currentUser)
                elif selectB=="4":
                    DeleteOneArticle(currentUser)
                elif selectB=="5":
                    EditOneArticle(currentUser)
                else:
                    currentUser=""
                    break
    else:
        #退出
        print("安全退出!")
        sys.exit()

Main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值