import requests from bs4 import BeautifulSoup import matplotlib.pyplot as plt import pandas as pd PLAYERS_LIMIT = 25 TABLE_CLASS_NAME = "players_table" plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False 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)为这段代码添加一个将数据写入excel的功能
时间: 2024-03-18 11:43:23 浏览: 103
import reimport requestsfrom bs4 import BeautifulSoupimport t
好的,可以使用pandas将数据写入Excel文件。可以在`plot_top_players_scores`函数中添加以下代码实现:
```python
def plot_top_players_scores(players, scores):
data = {"Player": players, "Score": scores}
df = pd.DataFrame(data)
# 将数据写入Excel文件
writer = pd.ExcelWriter('top_players_scores.xlsx')
df.to_excel(writer, index=False)
writer.save()
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()
```
这样就会在运行代码的同时生成一个名为`top_players_scores.xlsx`的Excel文件,并将获取到的球员得分数据写入该文件中。
阅读全文