课程:《Python程序设计》
班级: 1933
姓名: 白晨阳
学号:20193314
实验教师:王志强老师
实验日期:2021年6月13日
必修/选修: 公选课

实验内容:

Python综合应用:爬虫、数据处理、可视化、机器学习、神经网络、游戏、网络安全等。

实验要求:

(1)程序能运行,功能丰富。(需求提交源代码,并建议录制程序运行的视频)10分
(2)综合实践报告,要体现实验分析、设计、实现过程、结果等信息,格式规范,逻辑清晰,结构合理。10分。
(3)在实践报告中,需要对全课进行总结,并写课程感想体会、意见和建议等。5分

实验过程:

1:下面是一个爬虫的程序代码:
rom bs4 import BeautifulSoup
import re
import sys
import urllib
import xlwt
import sqlite3

def main():
'''主程序'''
baseurl = "https://movie.douban.com/top250?start="
datalist = getData(baseurl)
savepath = '豆瓣电影top250.xls'
saveData(savepath, datalist)

def askURL(url):
'''访问URL'''
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"
}
req = urllib.request.Request(url=url, headers=headers)
html = ""
try:
response = urllib.request.urlopen(req)
html = response.read().decode("utf-8")
return html
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)

def getData(baseurl):
'''获取数据'''
findLink = re.compile(r'')
findImg = re.compile(r'<img.src="(.?)"', re.S)
findTitle = re.compile(r'(.)')
findRating = re.compile(r'(.
)')
findJudge = re.compile(r'(\d)人评价')
findInq = re.compile((r'(.
)'))
findBd = re.compile(r'

(.*?)

', re.S)
datalist = []
for i in range(0, 11):
url = baseurl + str(i * 25)
html = askURL(url)

    soup = BeautifulSoup(html, "html.parser")
    for item in soup.find_all('div', class_="item"):
        # print(item)
        movie_data = []
        item = str(item)
        link = re.findall(findLink, item)[0]
        movie_data.append(link)
        img = re.findall(findImg, item)[0]
        movie_data.append(img)
        title = re.findall(findTitle, item)
        if (len(title) == 2):
            ctitle = title[0]
            movie_data.append(ctitle)
            otitle = title[1].replace("/", "")
            movie_data.append(otitle)
        else:
            movie_data.append(title[0])
            movie_data.append("")
        rating = re.findall(findRating, item)[0]
        movie_data.append(rating)
        judge = re.findall(findJudge, item)[0]
        movie_data.append(judge)

        inq = re.findall(findInq, item)
        if (len(inq) != 0):
            inq = inq[0].replace("。", "")
            movie_data.append(inq)
        else:
            movie_data.append("")
        bd = re.findall(findBd, item)[0]
        bd = re.sub('<br(\s+)?/>(\s+)?', "", bd)
        bd = re.sub("/", "", bd)
        movie_data.append(bd.strip())
        datalist.append(movie_data)

# print(datalist)
return datalist

def saveData(savepath, datalist):
'''保存数据'''
workbook = xlwt.Workbook(encoding="utf-8", style_compression=0)
worksheet = workbook.add_sheet("豆瓣电影Top250", cell_overwrite_ok=True)
col = ("电影详情链接", "图片链接", "电影中文名", "电影外文名", "评分", "评价数", "描述", "相关信息")
for i in range(0, 8):
worksheet.write(0, i, col[i])
for i in range(0, 250):
# print("第%条" %(i+1))
data = datalist[i]
for j in range(0, 8):
worksheet.write(i + 1, j, data[j])
workbook.save('豆瓣电影top250.xls')

if name == 'main':
'''程序入口'''
main()

2:下面是一个贪吃蛇的小游戏:
程序如下:
def main():
pygame.init()

snake_speed_clock = pygame.time.Clock()

screen = pygame.display.set_mode((windows_width, windows_height))

screen.fill(white)

pygame.display.set_caption("贪吃蛇~")

show_start_info(screen)

while True:
music()
running_game(screen, snake_speed_clock)
show_end_info(screen)
def running_game(screen,snake_speed_clock):

start_x = random.randint(3, map_width - 8) ##开始位置

start_y = random.randint(3, map_height - 8)

snake_coords = [{'x': start_x, 'y': start_y}, ##初始贪吃蛇
{'x': start_x - 1, 'y': start_y},
{'x': start_x - 2, 'y': start_y}]

direction = RIGHT ##开始时向右移动

food = get_random_location() ##实物随机位置

while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()

move_snake(direction, snake_coords) ##移动蛇

ret = snake_is_alive(snake_coords)
if not ret:
    gameover_music()
    break     ##蛇死了. 游戏结束
snake_is_eat_food(snake_coords, food) ##判断蛇是否吃到食物

screen.fill(BG_COLOR)
draw_snake(screen, snake_coords)
draw_food(screen, food)
show_score(screen, len(snake_coords) - 3)
pygame.display.update()
snake_speed_clock.tick(snake_speed) ##控制fps

def draw_food(screen, food):

x = food['x'] * cell_size
y = food['y'] * cell_size
appleRect = pygame.Rect(x, y, cell_size, cell_size)
pygame.draw.rect(screen, red, appleRect)
def draw_snake(screen, snake_coords):

for coord in snake_coords:
x = coord['x'] * cell_size
y = coord['y'] * cell_size
wormSegmentRect = pygame.Rect(x,y,cell_size,cell_size)
pygame.draw.rect(screen, dark_blue, wormSegmentRect)
wormInnerSegmentRect = pygame.Rect(x+4,y+4,cell_size - 8, cell_size - 8)
pygame.draw.rect(screen, blue, wormInnerSegmentRect)
def move_snake(direction, snake_coords):

if direction == UP:
newHead = {'x':snake_coords[HEAD]['x'], 'y':snake_coords[HEAD]['y'] - 1}
elif direction == DOWN:
newHead = {'x':snake_coords[HEAD]['x'], 'y':snake_coords[HEAD]['y'] + 1}
elif direction == LEFT:
newHead = {'x':snake_coords[HEAD]['x'] - 1, 'y':snake_coords[HEAD]['y']}
elif direction == RIGHT:
newHead = {'x':snake_coords[HEAD]['x'] + 1, 'y':snake_coords[HEAD]['y']}
snake_coords.insert(0, newHead)
def snake_is_alive(snake_coords):

tag = True

头坐标超出地图范围

if(snake_coords[HEAD]['x'] == -1
or snake_coords[HEAD]['x'] == map_width
or snake_coords[HEAD]['y'] == -1
or snake_coords[HEAD]['y'] == map_height):
tag = False

头坐标等于身体某节坐标

for snake_body in snake_coords[1:]:
if snake_body['x'] == snake_coords[HEAD]['x'] and snake_body['y'] == snake_coords[HEAD]['y']:
tag = False
return tag
def snake_is_eat_food(snake_coords, food):

if(snake_coords[HEAD]['x'] == food['x'] and snake_coords[HEAD]['y'] == food['y']):
## 重新生成食物
food['x'] = random.randint(0, map_width - 1)
food['y'] = random.randint(0, map_height - 1)
else:
del snake_coords[-1] ##如果没有吃到实物, 就向前移动, 那么尾部一格删掉
def get_random_location():

return {'x':random.randint(0, map_width - 1),'y':random.randint(0, map_height - 1)}
def show_start_info(screen):

创建Font字体对象,使用render方法写字

font = pygame.font.Font("simsun.ttc", 40)
tip = font.render('按任意键开始游戏', True,(65,105,255))

加载图片

gamestart = pygame.image.load('startlogo.jpg').convert()

通过blit方法输出在屏幕上

screen.blit(gamestart,(140, 30))
screen.blit(tip,(240, 550))

刷新屏幕

pygame.display.update()

while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN: ##任意键按下
return
if (event.key == K_ESCAPE): ##若为ESC,则终止程序
terminate()
else:
return
def show_end_info(screen):

font = pygame.font.Font("simsun.ttc", 40)
tip = font.render("按ESC退出游戏,按任意键重新开始游戏",True,(65,105,255))

gamestart = pygame.image.load('gameover.png')

screen.blit(gamestart,(60, 0))

screen.blit(tip,(80, 300))
pygame.display.update()

while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
else:
return
def show_score(screen, score):

font = pygame.font.Font("simsun.ttc", 30)
scoreSurf = font.render("得分:%s" % score, True, green)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (windows_width - 120, 10)
screen.blit(scoreSurf,scoreRect)
def terminate():

pygame.quit()
sys.exit()
实验结果:

实验问题:

问题1:编程能力不是很强
解决方案:在网上查资料和同学的帮助下解决(本次实验的贪吃蛇并非原创,而是在同学的基础的再加创新,解决了他以前一些漏洞)
问题2:部分程序模块没有
解决方案:去网页下载,用pycharm下载
问题3:贪吃蛇还有一些问题尚未解决(贪吃蛇的图片加载问题处理不了,未找到问题源头)

建议:

1:我觉得老师在上课的时候不必讲太多的硬性知识,应该侧重例子展示。
2:课上的例子我觉得可以结合一些热门来达到更好的效果,提高同学们注意力。
3:我觉得老师应该多布置一下作业,还有布置一下预习课程,这样课堂效果会提高一点
4:老师可以排一下位置,这样就可以不浪费宝贵的上课时间在考勤上了
5:老师上课可以多等等,保证学生都跟上

实验感想

在这里要感谢一下王志强老师,谢谢你把我带进python的大门,充实了我的课外生活,现在我每天都会去学习一点python小知识,感觉每天都过得充实而有趣,而且在与c语言的对比下,python显得更加简单可入门,但功能齐全。师父领进门,修行在个人,在接下来的时光中,我相信python会给我巨大的惊喜,我也将在python的道路上继续前行。

posted on 2021-06-13 11:21  woaiwolai  阅读(112)  评论(0编辑  收藏  举报