模拟NBA文字直播 V1.0
——从虎扑上近3年所有的NBA文字直播中随机选取一场进行播放
输出形式
源码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 6 15:36:25 2021
@author: Monkey_Chen
"""
# 模拟NBA文字直播——从虎扑上近3年所有的NBA文字直播中随机选取一场进行播放
import requests
from bs4 import BeautifulSoup
import bs4
import pandas as pd
import time
import random
import os
# 从虎扑爬取近三年任意一场NBA文字直播页面内容
def getHTMLText(url):
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
# 数据清洗
def fillList(ulist, html):
soup = BeautifulSoup(html, "lxml")
for tr in soup.find('div', class_ = "table_list_live playbyplay_td table_overflow").findChildren("tr"):
#print(tr)
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
if len(tds) < 4:
continue
tds[1].string = tds[1].string.replace('\n', '')
ulist.append([tds[0].string, tds[1].string, tds[2].string, tds[3].string])
# 数据格式化
def printUnivList(ulist, num):
file = open('/Users/air/Downloads/nba-temp-data.txt', 'w')
temp = ''
for i in range(num):
u = ulist[i]
if '.0"' in u[0]:
u[0] = '0:' + u[0].replace('.0"', '')
if '"' in u[0]:
u[0] = '0:' + u[0].replace('"', '')
file.write(u[0] + '\t' + u[1] + '\t' + u[2] + '\t' + u[3] + '\n')
temp = u[3]
file.write('0:00\t' + ' gameover\t' + '比赛结束\t' + temp)
file.close()
# 模拟文字直播
def Simulate_the_NBA_text_broadcast():
data = pd.read_table('/Users/air/Downloads/nba-temp-data.txt', sep = '\t', names = ['time', 'team', 'content', 'score'])
# 获取队名
teamName1 = data.loc[0]['team']
teamName2 = data.loc[1]['team']
print('现在开始{:^6}对{:^6}的比赛'.format(teamName1, teamName2))
temp = data.loc[0]
t = temp['time'].split(':')
c = eval(t[0])
d = eval(t[1])
for i in range(len(data)):
second = 0
temp = data.loc[i]
times = temp['time'].split(':')
# a, b为前一次输出的比赛时间点
a, b = c, d
# c, d为本次输出的比赛时间点
c = int(times[0])
d = int(times[1])
if c > a:
a = 12
# 每次输出间隔的秒数
second = (a - c) * 60 + b - d
time.sleep(second * 1.0)
print('{:<10}{:}{:}{:}{:>8}:{:}'.format(temp[0], teamName1, temp[3], teamName2, temp[1], temp[2]))
# 文字直播结束后删除数据文件
os.remove('/Users/air/Downloads/nba-temp-data.txt')
if __name__ == '__main__':
uinfo = []
# 选取任意一场比赛,生成url
gameNum = str(156000 + random.randint(1, 4267))
url = 'https://nba.hupu.com/games/playbyplay/' + gameNum
print(url)
html = getHTMLText(url)
fillList(uinfo, html)
printUnivList(uinfo, len(uinfo))
Simulate_the_NBA_text_broadcast()
nba-temp-data.txt的内容格式如下:
12:00 火箭 休斯顿火箭 阵容调整 (P.J. 塔克; 詹姆斯 哈登; 詹姆斯 恩尼斯; 克里斯 保罗; 克林特 卡佩拉) 0-0
12:00 爵士 犹他爵士 阵容调整 (瑞奇 卢比奥; 杰 克洛德; 鲁迪 戈波特; 多诺万 米切尔; 乔 英格尔斯) 0-0
12:00 火箭 克林特 卡佩拉 对阵 鲁迪 戈波特 (P.J. 塔克 获得控球权) 0-0
11:59 爵士 鲁迪 戈波特 个人犯规 0-0
11:39 火箭 克里斯 保罗 两分球进 2-0
11:26\t火箭\tP.J. 塔克 个人犯规\t2-0