import requests from bs4 import BeautifulSoup import matplotlib.pyplot as plt import pandas as pd plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False url = "https://nba.hupu.com/stats/players" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") players = [] scores = [] table = soup.find("table", class_="players_table") rows = table.find_all("tr") for row in rows[1:26]: cols = row.find_all("td") player = cols[1].text.strip() score_range = cols[4].text.strip() score_parts = score_range.split("-") min_score = float(score_parts[0]) max_score = float(score_parts[1]) score = int((min_score + max_score) / 2) players.append(player) scores.append(score) data = {"Player": players, "Score": scores} df = pd.DataFrame(data) fig, ax = plt.subplots(figsize=(12, 6)) ax.bar(players, scores, color='green', alpha=0.6) ax.set_xlabel('球员', fontsize=12) ax.set_ylabel('得分', fontsize=12) ax.set_title('NBA球员得分', fontsize=14) plt.xticks(rotation=45, ha='right', fontsize=8) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) for i, score in enumerate(scores): ax.text(i, score+0.5, str(score), ha='center', va='bottom') fig.tight_layout() plt.show()对这些代码做一些小的优化
时间: 2024-03-18 11:43:29 浏览: 107
import reimport requestsfrom bs4 import BeautifulSoupimport t
这段代码本身已经比较简洁,可以考虑做一些小的优化,包括:
1. 为了避免在代码中多次使用硬编码的数字和字符串,可以将它们定义为常量或变量,以提高代码的可读性和可维护性。比如,将“players_table”定义为一个常量,将球员数量限制为一个变量等等。
2. 可以考虑将整个代码块封装成一个函数,以提高代码的复用性和可维护性。
3. 如果只需要显示前25个球员的得分,可以将这个限制作为一个参数传入函数中,以便在需要时更改。
下面是一个根据上述优化建议进行修改的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import pandas as pd
PLAYERS_LIMIT = 25
TABLE_CLASS_NAME = "players_table"
def get_top_players_scores(limit=PLAYERS_LIMIT, table_class_name=TABLE_CLASS_NAME):
url = "https://nba.hupu.com/stats/players"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
players = []
scores = []
table = soup.find("table", class_=table_class_name)
rows = table.find_all("tr")
for row in rows[1:limit+1]:
cols = row.find_all("td")
player = cols[1].text.strip()
score_range = cols[4].text.strip()
score_parts = score_range.split("-")
min_score = float(score_parts[0])
max_score = float(score_parts[1])
score = int((min_score + max_score) / 2)
players.append(player)
scores.append(score)
return players, scores
def plot_top_players_scores(players, scores):
data = {"Player": players, "Score": scores}
df = pd.DataFrame(data)
fig, ax = plt.subplots(figsize=(12, 6))
ax.bar(players, scores, color='green', alpha=0.6)
ax.set_xlabel('球员', fontsize=12)
ax.set_ylabel('得分', fontsize=12)
ax.set_title('NBA球员得分', fontsize=14)
plt.xticks(rotation=45, ha='right', fontsize=8)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
for i, score in enumerate(scores):
ax.text(i, score+0.5, str(score), ha='center', va='bottom')
fig.tight_layout()
plt.show()
if __name__ == "__main__":
players, scores = get_top_players_scores()
plot_top_players_scores(players, scores)
```
阅读全文