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

如何从配置文件中获取API返回ID对应的描述信息?

实现思路与代码示例

这需求用Python来实现超顺手,分三个核心步骤就能搞定,我给你一步步拆解:

1. 提取API返回中的ID字段

首先从API返回的列表里把每个元素的id值提取出来,用列表推导式就能轻松搞定:

# 模拟API返回结果
api_response = [{'id': 'pc_fan_problem'}]
# 提取所有id字段
extracted_ids = [item['id'] for item in api_response]

2. 解析配置文件为字典

你的配置文件是类似键值对的格式,我们可以用正则表达式来匹配每个key="value"的条目,把它转换成Python字典,这样后续查找会非常方便:

import re

# 模拟配置文件内容
config_content = 'pc_fan_problem="i having problem with pc_fan_problem" pc_reset="i having problem with pc_reset" pc_battery_low="i having problem with pc_battery_low"'

# 用正则匹配所有键值对,格式为 键="值"
pattern = re.compile(r'(\w+)="([^"]+)"')
matches = pattern.findall(config_content)

# 转换成字典
config_dict = dict(matches)

这段正则的逻辑是:(\w+)匹配键名(字母数字下划线),"([^"]+)"匹配被双引号包裹的内容(确保不会把后面的引号也包含进去)。

3. 生成目标格式的结果

最后遍历提取到的ID,从配置字典里取出对应的描述,组装成你要的列表格式:

# 生成目标结果
final_result = [{id: config_dict[id]} for id in extracted_ids if id in config_dict]

print(final_result)
# 输出:[{'pc_fan_problem': 'i having problem with pc_fan_problem'}]

这里加了if id in config_dict的判断,是为了避免API返回的ID在配置文件中不存在时抛出KeyError,让代码更健壮。

完整代码整合

把上面的步骤整合到一起就是完整的实现:

import re

# 模拟API返回
api_response = [{'id': 'pc_fan_problem'}]
# 模拟配置文件内容
config_content = 'pc_fan_problem="i having problem with pc_fan_problem" pc_reset="i having problem with pc_reset" pc_battery_low="i having problem with pc_battery_low"'

# 步骤1:提取ID
extracted_ids = [item['id'] for item in api_response]

# 步骤2:解析配置为字典
pattern = re.compile(r'(\w+)="([^"]+)"')
config_dict = dict(pattern.findall(config_content))

# 步骤3:生成结果
final_result = [{id: config_dict[id]} for id in extracted_ids if id in config_dict]

print(final_result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 00:22:30