You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python API数据提取问题:多值返回与整数转换空格丢失求解

Python API数据处理问题解决方案

1. 让API返回单个值

你当前的API URL已经包含results=1,这会让ThingSpeak返回最近1条feed数据。如果你的“得到5个值”是指单条feed的field2字段里包含多个数值(比如格式类似"100 200 300 400 500 ppm"),问题出在数据源头:

  • 检查上传数据的设备代码,确保每次向ThingSpeak的field2字段上传单个数值,而非多个值拼接的字符串
  • 若需要获取历史单值数据,可调整URL的results参数(比如results=5会返回5条独立feed,每条的field2为单个值),但当前results=1已经是单条feed返回逻辑

2. 转换整数后保留数字间空格

原代码直接将带空格的字符串转成整数会报错,且单个整数无法包含空格。正确做法是拆分字符串、逐个转整数后再格式化输出,修改后的代码如下:

import requests
import json

url = "https://api.thingspeak.com/channels/1827200/fields/2.json?api_key=IVIRLPBRZ121YIGL&results=1"

def data_extraction():
    response = requests.get(url).text
    data = json.loads(response)
    feeds = data["feeds"][0]
    tds = feeds["field2"]
    
    # 清理字符串:移除ppm标识、换行符并去除首尾空白
    cleaned_tds = tds.replace("ppm", "").replace("\n", "").replace("\r", "").strip()
    
    # 分割字符串为单个数字,转换为整数列表(过滤非数字内容)
    int_tds_list = [int(num) for num in cleaned_tds.split() if num.isdigit()]
    
    # 用空格连接整数,还原带空格的格式输出
    formatted_output = " ".join(map(str, int_tds_list))
    print("带空格的整数输出:", formatted_output)
    
    # 若确认返回单个值,直接提取单个整数
    if len(int_tds_list) == 1:
        single_int_value = int_tds_list[0]
        print("单个整数输出:", single_int_value)

data_extraction()

关键修改说明:

  • 用split()按空格拆分清理后的字符串,得到独立的数字字符串
  • 通过列表推导式将每个数字字符串转为整数,同时过滤无效内容
  • 用" ".join(map(str, int_tds_list))将整数列表重新格式化为带空格的字符串输出
  • 若后续API返回单个值,可直接从列表中提取第一个元素作为单独整数使用

内容的提问来源于stack exchange,提问作者Akshat Aggarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:01:08