五大联赛积分榜查询工具
最近无事写了一个Python程序,用来查询五大联赛积分榜信息,写的过程中也学到了一些东西,效果如下:
其中用到了正则表达式,prettytable库,感觉这个输出效果还挺好的,哈哈,我是皇马球迷。代码就不贴了,挺简单的。
import urllib.request
import re
from prettytable import PrettyTable
global ran
def print_socre(l, teamname, rank,x):
l.insert(0,teamname)
l.append(rank)
x.add_row(l)
def check_lega(leganame):
if leganame in ['西甲', '意甲', '德甲', '法甲', '英超']:
return True
else:
return False
def get_html(leganame):
ligamap = {'西甲': '13', '英超': '4', '德甲': '15', '法甲': '16', '意甲': '3'}
url = 'http://sports1.sina.cn/global/scoreboard?league_type_id=' + ligamap[leganame] + '&vt=4'
response = urllib.request.urlopen(url)
html = response.read()
html = html.decode('utf-8')
return html
def get_teams(leganame):
teams = []
html = get_html(leganame)
a = html.find('w_40') + 400
b = html.find('历届积分榜')
html = html[a:b]
z = re.findall(u'(span\>)([A-Z]{0,2}[\u4e00-\u9fa5]{2,6}[0-9]{0,2})(\<)', html) # 匹配球队名称
for each in range(len(z)):
teams.append(z[each][1])
# print(z)
return teams
def find_data(data):
l = []
tem = re.findall(r'(\>)([0-9]{1,2})(\<)', data) # 获得球队具体数据
for i in range(5):
l.append(tem[i][1])
return l
def get_teaminfo(teamname, leganame,x): # 获取球队信息
html = get_html(leganame)
a = html.find(teamname) + 22
b = html.find('li', a) - 2
data = html[a:b] # 获取比赛信息
global ran
ran += 1
print_socre(find_data(data), teamname, str(ran),x)
def get_board(leganame):
x = PrettyTable(["球队", "已赛", "胜", "平", "负", "积分", "排名"])
x.padding_width = 1
x.align["球队"]="1"
teams = get_teams(leganame)
#print_lable()
for each in teams:
get_teaminfo(each, leganame,x)
print(x)
if __name__ == '__main__':
while (True):
leganame = input('请输入需要查询的联赛(西甲,意甲,德甲,法甲,英超):')
if check_lega(leganame):
ran = 0
get_board(leganame)
# break
else:
print('联赛输入错误,请重新输入!')
continue