查看新闻 , 登陆 , 点赞 , 评论

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import hashlib
import random
import os

USER_STATUS = False


def wrapper(arg):
def inner(*args, **kwargs):
if not USER_STATUS:
print('请登录后查看或操作!')
return
arg()
return

return inner


@wrapper
def good():
"""
点赞
:return:
"""
with open('news', 'r', encoding='utf-8')as f1, open('news(1)', 'w', encoding='utf-8')as f2:
for line in f1:
a, b, c, d = line.split(' ')
dic = {'title': a, 'content': b, 'good': c, 'talk': d}
if dic['title'].split('.')[0] == user:
dic['good'] = str(int(dic['good']) + 1)
new_line = ' '.join(dic.values())
f2.write(new_line)
f2.write(line)

return '你赞了该条新闻!'


@wrapper
def talk():
"""
评论
:return:
"""
content = input('请输入内容:')
with open('news', 'r', encoding='utf-8')as f1, open('news(1)', 'w', encoding='utf-8')as f2:
for line in f1:
a, b, c, d = line.split(' ')
e = d.strip()
dic = {'title': a, 'content': b, 'good': c, 'talk': e}
if dic['title'].split('.')[0] == '1':
dic['talk'] = '%s///%s:%s' % (e, user, content)
new_line = ' '.join(dic.values())
f2.write(' '+new_line)
os.remove('news')
os.rename('news(1)', 'news')
print('你评论了该条新闻!')
return


def get_md5(data):
"""
md5加密
:param data:
:return:
"""
obj = hashlib.md5("resdy54436jgfdsjdxff123ad".encode('utf-8'))
obj.update(data.encode('utf-8'))
result = obj.hexdigest()
return result


def login():
"""
用户登陆
:return:
"""
while 1:
username = input('请输入用户名(N/n退出):')
if username.upper() == 'N':
return
pwd = input('请输入密码:')
while 1:
s = ''
for i in range(4):
code = random.randint(65, 90)
new = chr(code)
s += new
print(s)
user2 = input('请输入验证码:')

if user2.upper() == s and username == 'alex' and get_md5(pwd) == get_md5('123'):
print('登陆成功!')
global USER_STATUS
USER_STATUS = username
return
elif user2.upper() == s:
print('用户名或密码错误!')
break
else:
print('验证码错误,请重新输入!')


def news():
"""
新闻列表
:return:
"""
while 1:
with open('news', 'r', encoding='utf-8') as f:
a = f.read().split(' ')
lst = []
for i in a:
title, content, dianzan, pinglun = i.split(' ')
print(title)
lst.append([content, dianzan, pinglun])
global user
user = input('查看详情请选择序号(N/n退出):')
if user.upper() == 'N':
return
if not user.isdigit():
print('输入有误,请重新输入!')
continue
user = int(user)
print(lst[user - 1][0])
print('已有%s人点赞.' % lst[user - 1][1])
for item in lst[user - 1][-1].split('///'):
print(item)

while 1:
xxx = input('点赞请按1,评论请按2,按N/n返回上一层:')
if xxx.upper() == 'N':
break
if not xxx.isdigit():
print('输入有误!请重新输入!')
continue
xxx = int(xxx)
dic = {1: good, 2: talk}
if dic.get(xxx) == None:
print('输入有误!请重新输入!')
continue
dic.get(xxx)()


def main():
"""
程序入口
:return:
"""
while True:
print("""欢迎使用本新闻系统!
1.用户登陆
2.新闻列表""")
dic = {1: login, 2: news}
user1 = input('请选择(N/n退出):')
if user1.upper() == 'N':
return
user1 = int(user1)
if user1 not in dic:
print('输入错误!')
continue
user1 = int(user1)
dic.get(user1)()


if __name__ == '__main__':
main()
原文地址:https://www.cnblogs.com/zjx1/p/10754411.html