T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 38 天:自然语言接口:健身记录写入表格

这是「Python 100 天」系列第 38 天的学习笔记:自然语言接口:健身记录写入表格。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

用一句自然语言("跑了 5 公里,做了 20 分钟俯卧撑")调用 Nutritionix 接口,它会解析出运动名称、时长、消耗卡路里;再通过 Sheety 把结果写进 Google 表格的一行。README 知识点:自然语言查询、写入表格(POST)、Basic Auth 认证、环境变量。

一、自然语言 API

1
2
3
4
payload = {
"query": "ran 5km and did 20 minutes of push ups",
"gender": "male", "weight_kg": 70, "height_cm": 175, "age": 25,
}

这类接口内部是 NLP 模型:把句子拆成"动作 + 数量",再按身高体重估算消耗。它返回的是一个列表,因为一句话里可能有多个动作:

1
result["exercises"]  # [{name, duration_min, nf_calories, ...}, ...]

所以下面必须用 for 遍历,不能假设只有一个。

二、Basic Auth

1
requests.post(url, json=payload, auth=("用户名", "密码"))

auth= 会自动生成 Authorization: Basic base64(user:pass) 请求头。base64 不是加密,只是编码,所以 Basic Auth 必须走 HTTPS。

三、写入表格的结构

Sheety 把 Google Sheet 的每一行映射成 JSON:

1
{"workout": {"date": "02/12/2026", "exercise": "Running", "duration": 30, "calories": 250}}

外层键 workout 是工作表的名字(单数形式),由 Sheety 生成,写错就 400。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import requests
from datetime import datetime
import os

APP_ID = os.environ['NUT_APP_ID']
API_KEY = os.environ['NUT_API_KEY']
GENDER = "male"
WEIGHT_KG = "KG as int"
HEIGHT_CM = "Height as int"
AGE = "Age as int"

nutritionix_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheety_endpoint = os.environ['SHEET_ENDPOINT']

headers = {
"x-app-id": APP_ID,
"x-app-key": API_KEY,
}

nutritionix_post_request = {
"query": input("Which exercise did you do today?"),
"gender": GENDER,
"weight_kg": WEIGHT_KG,
"height_cm": HEIGHT_CM,
"age": AGE,
}

response = requests.post(nutritionix_endpoint, json=nutritionix_post_request, headers=headers)
result = response.json()

today_date = datetime.now().strftime("%d/%m/%Y")
now_time = datetime.now().strftime("%X")

for exercise in result["exercises"]:
sheet_inputs = {
"workout": {
"date": today_date,
"time": now_time,
"exercise": exercise["name"].title(),
"duration": exercise["duration_min"],
"calories": exercise["nf_calories"]
}
}

sheet_response = requests.post(sheety_endpoint, json=sheet_inputs, auth=(os.environ['SHEET_USER'],
os.environ['SHEET_PW']))
print(sheet_response.text)

代码走读

  1. 四个环境变量:Nutritionix 的 app id / key、Sheety 的端点、用户名密码。
  2. GENDER、WEIGHT_KG 等是接口要求的上下文,缺了估算不准。作者留了字符串占位符 "KG as int",实际要换成数字。
  3. headers 里 x-app-id、x-app-key 是 Nutritionix 的自定义头。
  4. 一次 POST 拿到解析结果,再 for exercise in result["exercises"] 逐条写入表格。
  5. datetime.now().strftime("%d/%m/%Y") 生成 02/12/2026,%X 是本地时间(等价 %H:%M:%S)。

需要注意的地方

  • result["exercises"] 可能为空:说一句"今天很累"解析不出运动,列表就是空的,循环一次都不进(安全),但也没有任何反馈。
  • response.json() 前没有 raise_for_status():401(密钥错)时返回的是错误 JSON,result["exercises"] 直接 KeyError。
  • 每次都 datetime.now() 取两次:跨零点时日期和时间可能不一致,应该取一次存起来。
  • title() 处理运动名:"running" → "Running",好看但对数据统计没帮助(大小写不统一会导致分组错误,最好统一小写存储、显示时再美化)。

运行结果

Google 表格新增一行:

date time exercise duration calories
02/12/202619:32:10Running30250

易错点

  1. Sheety 的免费额度:每月 200 次请求,调试时要省着用。
  2. 工作表名:workout 必须和 Sheety 里配置的一致。
  3. 认证失败返回 401:auth 元组顺序是(用户名, 密码)。
  4. 数字当字符串发:weight_kg 传 "70" 有时能用,但按文档应传数字。

动手改

  • 把身高体重年龄做成 input() 或配置文件。
  • 加 raise_for_status() 和"没有识别到运动"的提示。
  • 写入前先 GET 一次,避免同一分钟重复记录。

源文件逐个讲解

2 个文件:main.py(48 行)、README.md(9 行)。

main.py(48 行)

结构:读 5 个环境变量 → 一句自然语言 → 两个 API(解析 + 写表)

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
from datetime import datetime
import os

APP_ID = os.environ['NUT_APP_ID']
API_KEY = os.environ['NUT_API_KEY']
GENDER = "male"
WEIGHT_KG = "KG as int"
HEIGHT_CM = "Height as int"
AGE = "Age as int"

nutritionix_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheety_endpoint = os.environ['SHEET_ENDPOINT']

注意这里用的是 os.environ['X'](方括号)而不是 .get()——Day 35 用的是 .get()。这里更好:变量没配就立刻 KeyError,不会等到请求时才报一个莫名其妙的 401。这就是「早失败」原则。

WEIGHT_KG = "KG as int" 是占位符字符串,作者没填真实体重。后果:nutritionix 收到 "weight_kg": "KG as int" 会返回 400。这三个常量必须改成数字。

(1)自然语言解析 API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
headers = {
"x-app-id": APP_ID,
"x-app-key": API_KEY,
}

nutritionix_post_request = {
"query": input("Which exercise did you do today?"),
"gender": GENDER,
"weight_kg": WEIGHT_KG,
"height_cm": HEIGHT_CM,
"age": AGE,
}

response = requests.post(nutritionix_endpoint, json=nutritionix_post_request, headers=headers)
result = response.json()

这个 API 的输入是「一句人话」:

1
"ran 3 miles and did 20 minutes of yoga"

输出是结构化的运动记录:

1
2
3
4
5
6
{
"exercises": [
{"name": "running", "duration_min": 30, "nf_calories": 350, ...},
{"name": "yoga", "duration_min": 20, "nf_calories": 90, ...}
]
}

这就是「自然语言接口」(NLP API)——你不用写解析器,一句话进去、结构化数据出来。这是这一天最值得记住的东西。

x-app-id / x-app-key 是自定义请求头(和 Day 37 的 X-USER-TOKEN 同类)。

「身体数据」是必须传的:卡路里计算依赖性别、体重、身高、年龄——同样的运动,不同人消耗不同。

(2)写进 Google Sheet(通过 Sheety)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
today_date = datetime.now().strftime("%d/%m/%Y")
now_time = datetime.now().strftime("%X")

for exercise in result["exercises"]:
sheet_inputs = {
"workout": {
"date": today_date,
"time": now_time,
"exercise": exercise["name"].title(),
"duration": exercise["duration_min"],
"calories": exercise["nf_calories"]
}
}

sheet_response = requests.post(sheety_endpoint, json=sheet_inputs, auth=(os.environ['SHEET_USER'],
os.environ['SHEET_PW']))
print(sheet_response.text)

四个要点:

  1. strftime("%d/%m/%Y") → 02/12/2026(英式日/月/年),%X → 14:30:05(本地时间的时分秒)。
  2. {"workout": {...}} 外面必须再包一层:Sheety 要求「表名 → 行数据」的结构。这是很多「表格 API」的固定格式。
  3. auth=(user, password):HTTP Basic Auth,requests 会自动做 base64 编码。和 Day 37 的 token 头是两种不同的认证方式。
  4. 循环里逐条 POST:一句话提到两个运动,就发两次请求、写两行。

exercise["name"].title() 把 "running" 变成 "Running"——只为表格好看。

这份代码的问题

  1. WEIGHT_KG/HEIGHT_CM/AGE 是占位符,跑不通。
  2. result["exercises"] 没有判空:没识别出运动时列表为空,循环不执行,用户以为程序没反应。
  3. response 没有 raise_for_status():解析失败时 result 里没有 exercises 键,直接 KeyError。
  4. 日期格式 %d/%m/%Y:写进 Google Sheet 后,如果表格区域设置是美国,会被解析成「月/日」——跨区域的日期格式是经典坑。
  5. 循环里没做异常处理:第二条写失败,前面的已经写进去了,状态不一致。

README.md(9 行)

标题 Day 38 - Workout Tracking Using Google Sheets,知识点:How to Use API Keys and Authentication with Nutritionix API、How to use Bearer Authentication、How to Work with the Sheety API、Post Requests to Google Sheets。

四条对应四段:Nutritionix 的 app-id/app-key、认证、Sheety、POST 写表。

注意 Bearer Authentication 这份代码里没用(用的是 Basic Auth 的 auth= 元组)——README 是课程大纲,不是这份代码的说明书。

文件间关系

1
2
3
用户一句话 ──POST──▶ Nutritionix(解析)──▶ exercises 列表
↓ 逐条
Sheety ──▶ Google Sheet

「一句话 → 结构化 → 落库」是这一天的形状。Day 53 的「爬数据 → 自动填表」是它的镜像:数据来源从「人说话」变成「网页」。

微信收款码 微信
支付宝收款码 支付宝
评论