Python是一种功能强大的编程语言,被广泛应用于数据分析、人工智能、网站开发等各个领域。它具有简洁易读的语法和丰富的库,让编程变得简单高效。若想更好地掌握Python,开启自己的创新之旅,不妨尝试一些具体的代码示例。
- 数据分析与可视化
import pandas as pd import matplotlib.pyplot as plt data = {'Name': ['Alice', 'Bob', 'Cathy', 'David'], 'Age': [25, 30, 35, 40]} df = pd.DataFrame(data) plt.bar(df['Name'], df['Age']) plt.xlabel('Name') plt.ylabel('Age') plt.title('Age Distribution') plt.show()
- 简单的爬虫
import requests from bs4 import BeautifulSoup url = 'http://example.com' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') print(soup.prettify())
- 机器学习实践
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = RandomForestClassifier() model.fit(X_train, y_train) predictions = model.predict(X_test) print('Accuracy:', accuracy_score(y_test, predictions))
通过这些简单的示例,你可以体验Python在数据分析、网络爬