Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
130 changes: 130 additions & 0 deletions homeworks/A13376/homework1/经济学人.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# -*- coding: utf-8 -*-

import codecs
import os
# 解决 'ascii' codec can't decode byte 0xe5的问题
import sys
reload(sys)
sys.setdefaultencoding('utf8')

#1. 读取文件
#['aa', 'aaa-bbb-sds'] => ['aa', 'aaa', 'bbb', 'sds']
def word_split(words):
new_list = []
for word in words:
if '-' not in word:
new_list.append(word)
else:
lst = word.split('-')
new_list.extend(lst)
return new_list


def read_file(file_path):
f = codecs.open(file_path, 'r') #打开文件
lines = f.readlines()
word_list = []
for line in lines:
line = line.strip()
words = line.split(" ") #用空格分割
words = word_split(words) #用-分割
word_list.extend(words)
return word_list

def get_file_from_folder(folder_path):
file_paths = []
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
file_paths.append(file_path)
return file_paths

#读取多文件里的单词
def read_files(file_paths):
final_words = []
for path in file_paths:
final_words.extend(read_file(path))
return final_words


#2.获取格式化之后的单词
def format_word(word):
fmt = 'abcdefghijklmnopqrstuvwxyz-'
for char in word:
if char not in fmt:
word = word.replace(char, '')
return word.lower()

def format_words(words):
word_list = []
for word in words:
wd = format_word(word)
if wd:
word_list.append(wd)
return word_list

#3. 统计单词数目
# {'aa':4, 'bb':1}
def statictcs_words(words):
s_word_dict = {}
for word in words:
if s_word_dict.has_key(word):
s_word_dict[word] = s_word_dict[word] + 1
else:
s_word_dict[word] = 1
#排序
sorted_dict = sorted(s_word_dict.iteritems(), key=lambda d: d[1], reverse=True)
return sorted_dict

#4.输出成csv
def print_to_csv(volcaulay_list, word_dict, to_file_path, total_count, start_and_end):
nfile = codecs.open(to_file_path, 'w+', "utf-8")
current_count = 0
for val in volcaulay_list:
num = val[1]
current_count = current_count + num
word_rate = (float(current_count)/total_count) * 100
meaning = u'未找到释义'
if val[0] in word_dict:
meaning = word_dict[val[0]]
#print ("%s,%s,%0.2f,%s\n" % (val[0], str(val[1]), word_rate, meaning))
if (word_rate/100 >= start_and_end[0]) and (word_rate/100 <= start_and_end[1]):
nfile.write("%s,%d,%0.2f,%s\n" % (val[0], val[1], word_rate, meaning))
nfile.close()

#5.读取词典文件
def read_dict(file_path):
f = codecs.open(file_path, 'r', "utf-8") #打开文件
lines = f.readlines()
word_dict = {}
for line in lines:
line = line.strip()
word, space, meaning = line.partition(' ') #以空格区分单词与释义
meaning = meaning.strip()
if word:
word_dict[word] = meaning
return word_dict


def main():
#1. 读取文本
words = read_files(get_file_from_folder('data1'))
print '获取了未格式化的单词 %d 个' % (len(words))

#2. 清洗文本
f_words = format_words(words)
total_word_count = len(f_words)
print '获取了已经格式化的单词 %d 个' %(len(f_words))

#3. 统计单词和排序
word_list = statictcs_words(f_words)

start_and_end = [0.5, 0.7] #截取这一部分的单词

word_dict = read_dict("8000-words.txt")

#4. 输出文件
print_to_csv(word_list, word_dict, 'output/test.csv', total_word_count, start_and_end)

if __name__ == "__main__":
main()
Binary file added homeworks/A13376/homework2/beach_ball.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
105 changes: 105 additions & 0 deletions homeworks/A13376/homework2/pygame_snake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# -*- coding: utf-8 -*-
import pygame
import random

SCALE = 20 #地图中有多少格
SIZE = 20 #每一格的大小
WIDTH = SCALE * SIZE
HEIGHT = SCALE * SIZE

DIRECT = [[0,-1],[-1,0],[0,1],[1,0]]
dirt = 1 #蛇前进的方向

snake = [[4,3],[5,3],[6,3]]
apple = [3,1]

def screen_show(screen):
screen.fill([0,0,0])
img = pygame.image.load("beach_ball.png") # 图片路径,一般和python源文件放在一个目录下
screen.blit(img, [80, 300])

font = pygame.font.Font(None, 50) # 字体None=默认字体,字号
text = font.render("YOU WILL LOSE", True, [255, 255, 255]) # render(text, antialias, color, background=None)
screen.blit(text, [60, 200]) # 显示对象 位置
for body in snake:
pygame.draw.rect(screen, [0, 255,0], [body[0]*SIZE,body[1]*SIZE, SIZE - 1, SIZE - 1])
pygame.draw.circle(screen, [255, 0, 0], [apple[0]*SIZE + SIZE / 2, apple[1]*SIZE + SIZE / 2], SIZE/2)
pygame.display.flip()

def snake_update():
global dirt
new_body = [0,0]
new_body[0] = (snake[0][0] + DIRECT[dirt][0]) % SCALE
new_body[1] = (snake[0][1] + DIRECT[dirt][1]) % SCALE
if new_body == apple:
snake.insert(0, new_body)
return True
else:
snake.insert(0, new_body)
snake.pop()
return False

def is_lose(screen):
if snake.count(snake[0]) >= 2:
screen.fill([0, 0, 0])
return True
return False

def new_apple():
apple[0] = random.randint(0,19)
apple[1] = random.randint(0,19)

def w_down_cb():
global dirt
if dirt % 2 !=0:
dirt = 0

def s_down_cb():
global dirt
if dirt % 2 != 0:
dirt = 2

def a_down_cb():
global dirt
if dirt % 2 != 1:
dirt = 1

def d_down_cb():
global dirt
if dirt % 2 != 1:
dirt = 3

def main():
pygame.init()
screen = pygame.display.set_mode([WIDTH, HEIGHT])
running = True

while running:
pygame.time.delay(200) # 200ms
if snake_update():
new_apple()

screen_show(screen)

if is_lose(screen):
screen.fill([0, 0, 0])
break

for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
w_down_cb()
elif event.key == pygame.K_s:
s_down_cb()
elif event.key == pygame.K_a:
a_down_cb()
elif event.key == pygame.K_d:
d_down_cb()
# YOU LOSE

pygame.quit()

if __name__ == '__main__':
main()
22 changes: 22 additions & 0 deletions homeworks/A13376/homework3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# uband-s2-seven
uband友班编程课程

#背景
应用轻量级web框架完成个人主页设计

#要求
小组页面:
0、基本元素:
头像-圆形,居中
背景图片
昵称-居中,uband红
1、自我介绍
2、相册
3、项目展示
4、留言板

#发布

#其他

#参考资料
2 changes: 2 additions & 0 deletions homeworks/A13376/homework3/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CSRF_ENABLED = True
SECRET_KEY = '123456'
Binary file added homeworks/A13376/homework3/config.pyc
Binary file not shown.
101 changes: 101 additions & 0 deletions homeworks/A13376/homework3/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# -*- coding: utf-8 -*-
from flask import Flask
from flask_wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import Required
from flask import render_template
import json
import time
import codecs
import os
from flask import request,redirect

app = Flask(__name__)
app.config.from_object('config')

# 初始化form
class MockCreate(Form):
note = StringField("note",[Required()])
student = StringField("student",[Required()])
submit = SubmitField("Submit")

# 读取留言文件信息
def read_note_txt(file_path):
BASE_DIR = os.path.dirname(__file__)
nfile = codecs.open(file_path, 'r', 'utf-8')
lines=nfile.readlines()
datas=[]
for line in lines:
line = line.strip()
data = line.split(",")
datas.append(data)
return datas
nfile.close()

def read_json_file(filepath):
file=open(filepath,"r+")
file_text=file.read()
data=json.loads(file_text)
return data

@app.route('/')
def index():
BASE_DIR = os.path.dirname(__file__)
data=read_json_file(BASE_DIR+'/static/data/index.json')
return render_template('index.html',data=data)


# 获取页面传过来的留言信息,写入文件并且返回首页
@app.route("/notes",methods=['GET','POST'])
def MockController():
form = MockCreate()
note = form.note.data
student=form.student.data
now=time.strftime("%Y-%m-%d", time.localtime())
data = {}
BASE_DIR = os.path.dirname(__file__)
data["note_time"] =now
data["note"] =note
file_path=BASE_DIR+'/static/data/'+student+'.txt'
nfile = codecs.open(file_path, 'a+', 'utf-8')
nfile.write("%s,%s\n" % (data["note"], data["note_time"]))
note=request.url_root
return redirect(note+'details/'+student)


@app.route('/details/<string:student_number>')
def details(student_number):
BASE_DIR = os.path.dirname(__file__)
data=read_json_file(BASE_DIR+'/static/data/index.json')
user_data={}
for item in data:
if student_number==item['student_number']:
file_path = BASE_DIR + '/static/data/' + item['student_number'] + '.txt'
notes = read_note_txt(file_path)
user_data=item
break
data = read_json_file(BASE_DIR + '/static/data/project.json')
pro_data = []
for item in data:
if student_number==item['student_number']:
pro_data=item["project_info"]
break
return render_template('details.html',data=user_data,note=notes,pro_data=pro_data)

# 跳转至项目信息页面
@app.route('/<string:student_number>/project/<int:number>')
def project(student_number,number):
BASE_DIR = os.path.dirname(__file__)
data = read_json_file(BASE_DIR + '/static/data/project.json')
project_data = {}
per_data={}
for item in data:
if student_number == item['student_number']:
project_data["project"]=item["project"][number]
per_data=item
break
return render_template('essay.html',data=per_data,pro_data=project_data)


if __name__ == '__main__':
app.run(debug=True)
Loading