Files
health-calculator/health_calculator.py
T
class03m12 ceed2e6460 实现健康计算器
- BMI:输入身高、体重,输出 BMI 值
- 每日热量需求:输入性别、年龄、身高、体重、每日步数,输出每日所需摄入量
- 每日健康食谱
2026-09-24 02:50:36 +00:00

511 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
健康计算器
==========
本文件包含三个计算器:
1) BMI 计算器
输入:身高、体重
输出:BMI 值及所属区间
2) 每日热量需求计算器
输入:性别、年龄、身高、体重、每日步数
输出:BMR / 活动系数 / 每日总消耗(TDEE) / 建议摄入量与三大营养素
3) 每日健康食谱
输入:同上(自动取目标热量)
输出:按目标热量反推的一日三餐 + 加餐,含每项份量与热量
用法:
python health_calculator.py bmi -H 175 -W 68
python health_calculator.py calorie -g 男 -a 40 -H 175 -W 68 -s 5000 --goal 维持
python health_calculator.py recipe -g 男 -a 40 -H 175 -W 68 -s 5000 --goal 维持
python health_calculator.py # 交互式菜单
判定标准:
· BMI :中国成人标准 WS/T 428-2013
偏瘦 < 18.5 ≤ 正常 < 24.0 ≤ 超重 < 28.0 ≤ 肥胖
· BMR :Mifflin-St Jeor 公式(美国营养与饮食学会推荐)
· 活动系数 PAL:按每日步数分档
· 食谱热量分配:早 25% / 午 35% / 晚 30% / 加餐固定
"""
import argparse
import sys
from typing import List, Optional, Tuple
# ===========================================================================
# 第一部分:BMI 计算器
# ===========================================================================
def classify(bmi: float) -> Tuple[str, str]:
"""按中国成人标准返回 (区间名称, 提示语)。"""
if bmi < 18.5:
return "偏瘦", "低于正常范围,建议适当增加营养摄入"
if bmi < 24.0:
return "正常", "处于健康范围,请继续保持"
if bmi < 28.0:
return "超重", "高于正常范围,建议控制饮食并增加运动"
return "肥胖", "明显高于正常范围,建议咨询专业医生或营养师"
def normal_weight_range(height_m: float) -> Tuple[float, float]:
"""返回该身高对应的正常体重区间(kg),按 BMI 18.5 ~ 23.9 反推。"""
return 18.5 * height_m ** 2, 23.9 * height_m ** 2
def calculate(height_m: float, weight_kg: float) -> float:
"""BMI = 体重(kg) / 身高(m) 的平方。"""
return weight_kg / (height_m ** 2)
def render_bmi(height_m: float, weight_kg: float) -> str:
"""生成 BMI 的完整输出文本。"""
bmi = calculate(height_m, weight_kg)
label, advice = classify(bmi)
low, high = normal_weight_range(height_m)
lines = [
"=" * 34,
" BMI 计算结果",
"=" * 34,
f" 身高 : {height_m * 100:.1f} cm",
f" 体重 : {weight_kg:.1f} kg",
f" BMI : {bmi:.1f}",
f" 所属区间 : {label}",
f" 正常体重 : {low:.1f} ~ {high:.1f} kg",
"-" * 34,
f" {advice}",
"=" * 34,
]
return "\n".join(lines)
# ===========================================================================
# 第二部分:每日热量需求计算器
# ===========================================================================
# 每日步数下限 → (活动系数 PAL, 活动水平名称)
# 顺序从高到低,取第一个满足 steps >= 阈值 的档位
STEP_LEVELS = [
(12500, 1.9, "极高活动"),
(10000, 1.725, "高度活动"),
(7500, 1.55, "中度活动"),
(5000, 1.375, "轻度活动"),
(0, 1.2, "久坐"),
]
# 目标相对维持量的热量增减(kcal/天)
GOALS = {
"维持": 0,
"减脂": -300,
"增肌": +300,
}
def normalize_gender(text: str) -> Optional[str]:
"""把各种写法统一成 '男' / '女',无法识别返回 None。"""
s = text.strip().lower()
if s in ("男", "m", "male", "1"):
return "男"
if s in ("女", "f", "female", "0"):
return "女"
return None
def pal_for_steps(steps: int) -> Tuple[float, str]:
"""按每日步数返回 (活动系数 PAL, 活动水平名称)。"""
for threshold, pal, label in STEP_LEVELS:
if steps >= threshold:
return pal, label
return 1.2, "久坐"
def calc_bmr(gender: str, weight_kg: float, height_cm: float, age: int) -> float:
"""Mifflin-St Jeor 公式计算基础代谢率。"""
base = 10 * weight_kg + 6.25 * height_cm - 5 * age
return base + 5 if gender == "男" else base - 161
def calc_tdee(bmr: float, pal: float) -> float:
"""每日总消耗 = 基础代谢 × 活动系数。"""
return bmr * pal
def target_kcal(gender: str, age: int, height_cm: float,
weight_kg: float, steps: int, goal: str = "维持") -> float:
"""按性别、年龄、身高、体重、步数与目标,算出建议摄入热量。"""
bmr = calc_bmr(gender, weight_kg, height_cm, age)
pal, _ = pal_for_steps(steps)
return calc_tdee(bmr, pal) + GOALS.get(goal, 0)
def macro_split(kcal: float) -> Tuple[float, float, float]:
"""按 蛋白 20% / 脂肪 27% / 碳水 53% 换算克数。
蛋白和碳水 4 kcal/g,脂肪 9 kcal/g。"""
protein = kcal * 0.20 / 4
fat = kcal * 0.27 / 9
carb = kcal * 0.53 / 4
return protein, fat, carb
def render_calorie(gender: str, age: int, height_cm: float,
weight_kg: float, steps: int, goal: str = "维持") -> str:
"""生成每日热量需求的完整输出文本。"""
bmr = calc_bmr(gender, weight_kg, height_cm, age)
pal, level = pal_for_steps(steps)
tdee = calc_tdee(bmr, pal)
target = tdee + GOALS.get(goal, 0)
protein, fat, carb = macro_split(target)
lines = [
"=" * 40,
" 每日热量需求计算结果",
"=" * 40,
f" 性别 / 年龄 : {gender} / {age} 岁",
f" 身高 / 体重 : {height_cm:.1f} cm / {weight_kg:.1f} kg",
f" 每日步数 : {steps:,} 步",
"-" * 40,
f" 基础代谢 BMR : {bmr:,.0f} kcal",
f" 活动系数 PAL : {pal}({level})",
f" 每日总消耗 : {tdee:,.0f} kcal ← 维持当前体重",
"-" * 40,
f" 目标({goal}): {target:,.0f} kcal",
f" 蛋白质 : {protein:.0f} g",
f" 脂肪 : {fat:.0f} g",
f" 碳水化合物 : {carb:.0f} g",
]
# 安全下限提醒:长期摄入低于此值可能损害代谢
floor = 1200 if gender == "女" else 1500
if target < floor:
lines += [
"-" * 40,
f" ⚠ 低于安全下限 {floor} kcal。长期如此可能降低代谢、流失肌肉,",
" 建议通过增加活动量(提高步数)扩大消耗,而非继续压低摄入。",
]
lines.append("=" * 40)
return "\n".join(lines)
# ===========================================================================
# 第三部分:每日健康食谱
# ===========================================================================
# 固定项:(名称, 份量描述, 热量 kcal)
# 可调项:(名称, 每 100 g 热量 kcal, 占本餐可调热量百分比)
# —— 可调项的克数由「本餐目标热量 − 固定项热量」反推,自动适配不同热量目标
SNACK = [
("无糖酸奶", "150 g", 90),
("苹果", "200 g(约 1 个)", 104),
("混合坚果", "10 g(约 7 颗杏仁)", 60),
]
MEAL_TEMPLATE = [
("早餐", 25, [
("燕麦片", 380, 50),
("全麦面包", 250, 50),
], [
("无糖豆浆", "300 ml", 90),
("水煮蛋", "1 个(约 50 g)", 72),
("小番茄", "100 g", 20),
]),
("午餐", 35, [
("杂粮饭(熟)", 120, 55),
("鸡胸肉(熟)", 133, 45),
], [
("清炒时蔬", "300 g", 90),
("烹调油", "10 g", 90),
]),
("晚餐", 30, [
("杂粮饭(熟)", 120, 55),
("清蒸鱼", 105, 45),
], [
("蒜蓉青菜", "300 g", 84),
("烹调油", "8 g", 72),
]),
]
def round_to(value: float, step: int = 5) -> int:
"""把克数四舍五入到最接近的 step(默认 5 g),便于实际称量。"""
return int(round(value / step) * step)
def render_meal_plan(target: float) -> str:
"""按目标热量反推一日食谱,返回可直接打印的文本。"""
snack_kcal = sum(k for _, _, k in SNACK)
remaining = target - snack_kcal
ratio_sum = sum(r for _, r, _, _ in MEAL_TEMPLATE)
lines = [
"=" * 44,
" 每日健康食谱",
"=" * 44,
f" 目标热量:{target:,.0f} kcal",
f" 分配比例:早 25% / 午 35% / 晚 30% / 加餐固定",
"=" * 44,
]
total = 0.0
low_flag = False
for meal_name, ratio, adjustable, fixed in MEAL_TEMPLATE:
meal_target = remaining * ratio / ratio_sum
fixed_kcal = sum(k for _, _, k in fixed)
adjustable_kcal = meal_target - fixed_kcal
if adjustable_kcal <= 0:
low_flag = True
adjustable_kcal = 0
lines.append("")
lines.append(f" 【{meal_name}】目标 {meal_target:,.0f} kcal")
lines.append(" " + "-" * 40)
meal_total = fixed_kcal
for item, per100, share in adjustable:
need = adjustable_kcal * share / 100
grams = round_to(need / (per100 / 100)) if per100 else 0
if grams < 20:
grams = 20
low_flag = True
kcal = grams * per100 / 100
meal_total += kcal
lines.append(f" · {item}:{grams} g → {kcal:,.0f} kcal")
for item, portion, kcal in fixed:
lines.append(f" · {item}:{portion} → {kcal:,.0f} kcal")
lines.append(f" 小计:{meal_total:,.0f} kcal")
total += meal_total
# 加餐
lines.append("")
lines.append(" 【加餐】")
lines.append(" " + "-" * 40)
for item, portion, kcal in SNACK:
lines.append(f" · {item}:{portion} → {kcal:,.0f} kcal")
lines.append(f" 小计:{snack_kcal:,.0f} kcal")
total += snack_kcal
lines += [
"",
"=" * 44,
f" 全天合计:{total:,.0f} kcal(目标 {target:,.0f} kcal,"
f"偏差 {total - target:+.0f})",
"=" * 44,
]
if low_flag:
lines += [
" ⚠ 目标热量偏低,部分食材已按下限保留。建议提高活动量而非继续减食。",
"=" * 44,
]
lines += [
" 说明:",
" · 主食/蛋白质克数为生熟换算后的可称量值,蔬菜均为生重。",
" · 吃法顺序建议:蔬菜 → 蛋白质 → 主食,有助血糖平稳。",
" · 同类可互换:鸡胸↔鱼虾↔瘦牛猪,杂粮饭↔红薯↔玉米。",
" · 以上为一般性营养建议,如有基础疾病请遵医嘱。",
]
return "\n".join(lines)
# ===========================================================================
# 公共输入工具
# ===========================================================================
def to_meters(height: float) -> float:
"""把身高统一换算为米:大于 3 视为厘米,否则视为米。"""
return height / 100.0 if height > 3 else height
def validate(height_m: float, weight_kg: float) -> Optional[str]:
"""返回错误信息;校验通过则返回 None。"""
if not (0.5 <= height_m <= 2.8):
return f"身高 {height_m * 100:.1f} cm 超出合理范围(50 ~ 280 cm)。"
if not (2.0 <= weight_kg <= 500.0):
return f"体重 {weight_kg:.1f} kg 超出合理范围(2 ~ 500 kg)。"
return None
def ask(prompt: str) -> float:
"""交互式读取一个正数,输入非法时重新询问。"""
while True:
raw = input(prompt).strip()
try:
value = float(raw)
except ValueError:
print(" ✗ 请输入数字,例如 175")
continue
if value <= 0:
print(" ✗ 请输入大于 0 的数值")
continue
return value
def ask_text(prompt: str) -> str:
"""交互式读取一行文本。"""
return input(prompt).strip()
def check_profile(gender_raw: str, age: int, height_raw: float,
weight_raw: float, steps: int) -> Tuple[Optional[str], Optional[str]]:
"""校验性别/年龄/身高/体重/步数,返回 (错误信息, 规范化性别)。"""
gender = normalize_gender(gender_raw)
if gender is None:
return "性别无法识别:请输入 男 或 女。", None
if not (10 <= age <= 120):
return f"年龄 {age} 超出合理范围(10 ~ 120 岁)。", None
error = validate(to_meters(height_raw), weight_raw)
if error:
return error, None
if steps < 0:
return "每日步数不能为负数。", None
return None, gender
# ===========================================================================
# 运行入口
# ===========================================================================
def run_bmi(height_raw: float, weight_raw: float) -> int:
"""执行 BMI 计算,返回退出码。"""
height_m = to_meters(height_raw)
error = validate(height_m, weight_raw)
if error:
print(f"✗ 输入有误:{error}", file=sys.stderr)
return 1
print()
print(render_bmi(height_m, weight_raw))
return 0
def run_calorie(gender_raw: str, age: int, height_raw: float,
weight_raw: float, steps: int, goal: str = "维持") -> int:
"""执行每日热量需求计算,返回退出码。"""
error, gender = check_profile(gender_raw, age, height_raw, weight_raw, steps)
if error:
print(f"✗ {error}", file=sys.stderr)
return 1
if goal not in GOALS:
goal = "维持"
print()
print(render_calorie(gender, age, to_meters(height_raw) * 100,
weight_raw, steps, goal))
return 0
def run_recipe(gender_raw: str, age: int, height_raw: float,
weight_raw: float, steps: int, goal: str = "维持") -> int:
"""执行每日热量计算 + 食谱生成,返回退出码。"""
error, gender = check_profile(gender_raw, age, height_raw, weight_raw, steps)
if error:
print(f"✗ {error}", file=sys.stderr)
return 1
if goal not in GOALS:
goal = "维持"
height_cm = to_meters(height_raw) * 100
target = target_kcal(gender, age, height_cm, weight_raw, steps, goal)
print()
print(render_calorie(gender, age, height_cm, weight_raw, steps, goal))
print()
print(render_meal_plan(target))
return 0
def interactive_menu() -> None:
"""无参数运行时进入交互式菜单。"""
print("=" * 40)
print(" 健康计算器")
print("=" * 40)
print(" 1. 计算 BMI")
print(" 2. 计算每日热量需求")
print(" 3. 生成每日健康食谱")
print(" 0. 退出")
print("-" * 40)
while True:
choice = ask_text("请选择 > ")
if choice in ("0", "q", "退出"):
print("再见!")
return
if choice == "1":
run_bmi(
ask("请输入身高(厘米,如 175): "),
ask("请输入体重(千克,如 68): "),
)
elif choice in ("2", "3"):
gender = ask_text("请输入性别(男/女): ")
age = int(ask("请输入年龄(岁,如 40): "))
height = ask("请输入身高(厘米,如 175): ")
weight = ask("请输入体重(千克,如 68): ")
steps = int(ask("请输入每日步数(如 5000): "))
goal = ask_text("请输入目标(维持/减脂/增肌,回车默认维持): ") or "维持"
if choice == "2":
run_calorie(gender, age, height, weight, steps, goal)
else:
run_recipe(gender, age, height, weight, steps, goal)
else:
print("⚠ 无效选择,请输入 1、2、3 或 0。")
continue
print()
print("-" * 40)
def main() -> None:
parser = argparse.ArgumentParser(
prog="health_calculator",
description="健康计算器:BMI 计算 + 每日热量需求 + 每日健康食谱。",
)
sub = parser.add_subparsers(dest="cmd")
# 子命令:bmi
p_bmi = sub.add_parser("bmi", help="计算 BMI 值")
p_bmi.add_argument("-H", "--height", type=float,
help="身高,单位厘米(如 175)或米(如 1.75)")
p_bmi.add_argument("-W", "--weight", type=float, help="体重,单位千克")
# 子命令:calorie / recipe 共用一组个人参数
def add_profile_args(p: argparse.ArgumentParser) -> None:
p.add_argument("-g", "--gender", help="性别:男 / 女")
p.add_argument("-a", "--age", type=int, help="年龄(岁)")
p.add_argument("-H", "--height", type=float,
help="身高,单位厘米(如 175)或米(如 1.75)")
p.add_argument("-W", "--weight", type=float, help="体重,单位千克")
p.add_argument("-s", "--steps", type=int, default=5000,
help="每日步数(默认 5000)")
p.add_argument("--goal", choices=list(GOALS), default="维持",
help="目标:维持 / 减脂 / 增肌(默认 维持)")
p_cal = sub.add_parser("calorie", help="计算每日热量需求")
add_profile_args(p_cal)
p_rec = sub.add_parser("recipe", help="生成每日健康食谱")
add_profile_args(p_rec)
args = parser.parse_args()
if args.cmd == "bmi":
height = args.height if args.height is not None else ask("请输入身高(厘米,如 175): ")
weight = args.weight if args.weight is not None else ask("请输入体重(千克,如 68): ")
sys.exit(run_bmi(height, weight))
if args.cmd in ("calorie", "recipe"):
gender = args.gender if args.gender else ask_text("请输入性别(男/女): ")
age = args.age if args.age is not None else int(ask("请输入年龄(岁,如 40): "))
height = args.height if args.height is not None else ask("请输入身高(厘米,如 175): ")
weight = args.weight if args.weight is not None else ask("请输入体重(千克,如 68): ")
runner = run_calorie if args.cmd == "calorie" else run_recipe
sys.exit(runner(gender, age, height, weight, args.steps, args.goal))
# 未提供子命令 → 交互式菜单
interactive_menu()
if __name__ == "__main__":
main()