在Python中,你可以通过以下几种方法来编写关于四季的程序:
古诗生成
使用函数根据输入的季节生成相应的古诗。
```python
def generate_poem(season):
if season == "春":
poem = "春眠不觉晓,处处闻啼鸟。夜来风雨声,花落知多少。"
elif season == "夏":
poem = "蝉噪林逾静,鸟鸣山更幽。小荷才露尖尖角,早有蜻蜓立上头。"
elif season == "秋":
poem = "空山新雨后,天气晚来秋。明月松间照,清泉石上流。"
elif season == "冬":
poem = "北风卷地白草折,胡天八月即飞雪。忽如一夜春风来,千树万树梨花开。"
else:
poem = "输入的季节有误,请输入春、夏、秋、冬。"
return poem
print(generate_poem("春"))
print(generate_poem("夏"))
print(generate_poem("秋"))
print(generate_poem("冬"))
月份判断季节
根据输入的月份判断并输出对应的季节。
```python
def get_season(month):
if month in [3, 4, 5]:
return "春季"
elif month in [6, 7, 8]:
return "夏季"
elif month in [9, 10, 11]:
return "秋季"
else:
return "冬季"
获取当前月份
from datetime import datetime
current_month = datetime.now().month
判断当前季节
current_season = get_season(current_month)
print(f"当前季节是:{current_season}")
绘制季节图
使用数据可视化库(如matplotlib)绘制展示季节性变化的可视化图表。
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
设置中文字体
font_path = "C:/Windows/Fonts/simhei.ttf" Windows系统的字体路径
font_path = "/System/Library/Fonts/STHeiti Medium.ttc" macOS系统的字体路径
my_font = fm.FontProperties(fname=font_path)
生成示例数据
np.random.seed(0)
dates = pd.date_range("2020-01-01", periods=365 * 3) 3年数据
values = np.random.rand(len(dates)) * 100 创建DataFrame
df = pd.DataFrame({"date": dates, "value": values})
绘制季节图
df.set_index("date", inplace=True)
df.resample("M").sum().plot(kind="bar", figsize=(10, 6))
plt.title("Seasonal Plot", fontproperties=my_font)
plt.xlabel("Month", fontproperties=my_font)
plt.ylabel("Value", fontproperties=my_font)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
以上代码展示了如何使用Python来处理与季节相关的任务,包括古诗生成、月份到季节的映射以及绘制季节图。你可以根据自己的需求选择合适的方法进行实现