0Pricing
AI Prompt Engineering · 课时

请求表格与结构化数据

请求使用 Markdown 表格和结构化输出完成比较任务

请求表格与结构化数据 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

表格作为输出格式

对于比较信息,表格是最有用的 AI 输出格式之一。它们能让项目之间的关系一目了然,并支持快速并排分析。

获取高质量表格的关键在于:明确指定确切的列名、每列应包含的内容,以及要包含多少行。

基本表格请求

请求 Markdown 表格的标准模式:

“请将内容格式化为 Markdown 表格,列名为:[列 1]、[列 2]、[列 3]。”

Markdown 表格可以在 GitHub、Notion、Obsidian 以及大多数 AI 聊天界面中呈现。它们使用竖线分隔列,并使用短横线分隔表头。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Compare Python, JavaScript, and Go for building REST APIs. '
            'Format as a markdown table with columns: '
            'Language, Performance, Learning Curve, Ecosystem, Best Use Case. '
            'One row per language. Be concise — max 8 words per cell.'
        )
    }]
)
print(response.choices[0].message.content)

比较表格

在多个选项之间进行选择时,比较表格非常理想。您可以这样请求:

  • “请创建一个比较 X、Y 和 Z 的表格……”
  • “请制作一张……的功能比较表”
  • “请创建一张比较……优缺点的表格”

将选项作为行、评估标准作为列;也可以反过来,具体取决于哪种布局更适合您的内容阅读。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=400,
    messages=[{
        'role': 'user',
        'content': (
            'Create a comparison table for three cloud database options: '
            'Supabase, PlanetScale, and Neon.\n'
            'Rows: one per database.\n'
            'Columns: Free tier storage, Scaling model, Pricing at 10GB, '
            'Branching support, SQL compatibility.\n'
            'Format: markdown table. Cell content: max 6 words each.'
        )
    }]
)
print(response.content[0].text)

功能矩阵表格

功能矩阵是一种表格:行表示项目,列表示功能,每个单元格显示勾选标记、分数或简短数值。常见用途包括:

  • 跨版本或竞争产品进行软件功能比较
  • 比较 SaaS 产品的方案
  • 技术支持矩阵(哪些浏览器或 OS 支持哪些功能)

请求示例:“请创建一张功能矩阵表,为每项功能使用勾选标记(是/否)。”

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Create a feature matrix table for our SaaS pricing tiers: Free, Pro, Enterprise.\n'
            'Rows: API access, Custom domains, SSO login, SLA guarantee, Priority support, '
            'Data export, Team collaboration, Audit logs.\n'
            'Columns: Free, Pro, Enterprise.\n'
            'Use: YES / NO / PARTIAL for each cell.\n'
            'Format: markdown table.'
        )
    }]
)
print(response.choices[0].message.content)

从文本生成数据表格

一种非常实用的模式是要求模型从非结构化文本中提取信息,并将其格式化为表格。这本质上是由 AI 驱动的数据解析:

“请从下面的文本中提取以下信息,并将其格式化为包含 X、Y、Z 列的表格。”

请始终明确指定列名,以获得一致的结构。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

meeting_notes = (
    'Sarah will handle the API documentation by next Friday. '
    'John needs to fix the authentication bug — aim for Wednesday. '
    'Maria is responsible for the mobile UI update, due in 2 weeks. '
    'The DevOps team (lead: Alex) must set up staging by Monday. '
    'Carlos will write unit tests — deadline: end of sprint (Thursday).'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=300,
    messages=[{
        'role': 'user',
        'content': (
            'Extract all action items from the meeting notes below. '
            'Format as a markdown table with columns: Task, Owner, Deadline.\n\n'
            f'Meeting notes:\n{meeting_notes}'
        )
    }]
)
print(response.content[0].text)

CSV 输出

如果您需要将数据导入电子表格、数据库或用于进一步处理,请请求输出 CSV(逗号分隔值),而不是 Markdown 表格。

“请输出为带表头行的 CSV 数据行”或“请格式化为 CSV。第一行:列标题。”

CSV 具有良好的可移植性,可以直接粘贴到 Excel 或 Google Sheets 中,也可以由代码解析。

import openai
import csv
import io

client = openai.OpenAI(api_key='sk-your-key-here')

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Generate 5 sample customer support tickets for an e-commerce store. '
            'Output as CSV with header row. '
            'Columns: ticket_id, customer_name, issue_type, priority, status. '
            'issue_type values: SHIPPING / BILLING / PRODUCT / RETURNS. '
            'priority values: LOW / MEDIUM / HIGH. '
            'status values: OPEN / IN_PROGRESS / RESOLVED. '
            'No markdown formatting — raw CSV only.'
        )
    }]
)

csv_text = response.choices[0].message.content.strip()
reader = csv.DictReader(io.StringIO(csv_text))
for row in reader:
    print(row)

JSON 结构化输出

对于程序化使用,JSON 通常是最佳格式。请明确提出请求:

“请输出一个包含 X、Y、Z 键的 JSON 对象。”
“请返回一个 JSON 数组,其中每个元素都包含 A、B、C 属性。”

部分模型支持原生 JSON 模式,可以保证输出有效的 JSON;但即使没有该模式,明确请求 JSON 并说明架构,通常也能生成可解析的输出。

import anthropic
import json

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=400,
    messages=[{
        'role': 'user',
        'content': (
            'Generate 3 fictional user profiles for testing a fitness app. '
            'Output as a JSON array. '
            'Each object must have exactly these keys: '
            'id (integer), name (string), age (integer 18-65), '
            'fitness_level ("BEGINNER" | "INTERMEDIATE" | "ADVANCED"), '
            'goals (array of strings, max 3), weekly_sessions (integer 1-7). '
            'Output raw JSON only — no explanation, no markdown code fences.'
        )
    }]
)

try:
    data = json.loads(response.content[0].text)
    print(f'Parsed {len(data)} profiles successfully.')
    for profile in data:
        print(f'  {profile["name"]}, {profile["age"]}, {profile["fitness_level"]}')
except json.JSONDecodeError as e:
    print('JSON parse error:', e)

指定单元格内容规则

当您定义每个单元格中允许包含的内容时,表格质量会显著提升:

  • “每个单元格最多 5 个词”——防止单元格内容过于冗长而破坏表格格式
  • “仅允许是/否”——二元功能矩阵
  • “仅填写金额,不作解释”——简洁的价格表
  • “仅填写一个词”——强制简洁
  • “评分范围为 1 至 10”——数值评分表
import openai

client = openai.OpenAI(api_key='sk-your-key-here')

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Rate the following programming languages for these criteria.\n'
            'Languages (rows): Python, Rust, TypeScript, Go.\n'
            'Criteria (columns): Speed, Safety, Developer Experience, Job Market, Learning Curve.\n'
            'Cell format: integer score 1-10 only. No words, no explanation inside cells.\n'
            'After the table, add one sentence explaining your scoring philosophy.'
        )
    }]
)
print(response.choices[0].message.content)

转置表格

有时,默认的行列方向并不适合您的数据。转置表格会交换行和列——当属性很多而项目很少时非常有用。

请求示例:“创建一个以项目为列、属性为行的表格”或“转置表格,使 X 成为列。”

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=300,
    messages=[{
        'role': 'user',
        'content': (
            'Compare two job candidates: Alice and Bob. '
            'Create a transposed table where candidates are COLUMNS and attributes are ROWS. '
            'Attributes (rows): Years Experience, Primary Language, Education, '
            'Previous Employer, Salary Expectation Range. '
            'Format: markdown table. Cell content: factual, max 6 words.\n\n'
            'Alice: 7 years Python/ML, MS Computer Science MIT, ex-Google, expects $180-220k.\n'
            'Bob: 4 years JavaScript/Node, BS from UC Berkeley, ex-Stripe startup, expects $140-170k.'
        )
    }]
)
print(response.content[0].text)

何时 NOT 使用表格

表格并非总是合适的格式。以下情况应避免使用表格:

  • 只有 2 个项目——简短的段落比较更易阅读
  • 单元格内容长度差异很大——表格会变得难以阅读
  • 输出将用于纯文本环境(电子邮件正文、SMS)
  • 正在生成用于语音输出的内容
  • 项目之间是层级关系,而不是表格关系(此时应改用嵌套列表)
import openai

client = openai.OpenAI(api_key='sk-your-key-here')

# Table works: structured comparison
table_prompt = (
    'Compare MySQL vs PostgreSQL. '
    'Format: markdown table, columns: Feature, MySQL, PostgreSQL. '
    '6 rows covering: JSON support, Full-text search, Replication, Transactions, License, Best for.'
)

# No table needed: simple 2-option choice with prose reasoning
not_table_prompt = (
    'Should I use SQLite or PostgreSQL for a personal hobby project '
    'that will have at most 5 users? 2-sentence answer, no table.'
)

for label, prompt in [('TABLE APPROPRIATE', table_prompt), ('TABLE OVERKILL', not_table_prompt)]:
    response = client.chat.completions.create(
        model='gpt-4o', max_tokens=200,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'--- {label} ---')
    print(response.choices[0].message.content.strip()[:300])
    print()

将表格与其他格式结合

表格与周围的说明文字或列表搭配效果很好。一种常见的高质量输出结构是:

  1. 用简短的介绍段落说明比较标准
  2. 提供表格,方便快速浏览
  3. 用推荐段落给出最终结论

请明确提出这一要求:“请包含:1 句介绍、表格,然后是 2 句推荐。”

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=500,
    messages=[{
        'role': 'user',
        'content': (
            'Compare three Python testing frameworks: pytest, unittest, and nose2. '
            'Structure your response as:\n'
            '1. One-sentence intro explaining the comparison scope.\n'
            '2. Markdown table: columns = Framework, Ease of Use, Plugin Ecosystem, '
            'Speed, Community Activity. Rows = one per framework.\n'
            '3. One-sentence recommendation for a team starting a new project.'
        )
    }]
)
print(response.content[0].text)

知识检查

一位开发人员想使用 AI 为数据库测试生成示例数据。他们需要 10 行客户数据,字段包括 ID、姓名、电子邮件、国家和账户等级。应该请求哪种最佳输出格式?

表格和结构化数据——回顾

表格和结构化数据请求可以解锁 AI 最有用的一些输出格式。关键技巧包括:

  • 指定确切的列名,以获得一致的结构
  • 使用比较表格并排分析不同选项
  • 当数据将由程序处理时使用 CSV
  • 将数据集成到 API 并供代码使用时使用 JSON
  • 定义单元格内容规则:最大词数、允许的值、评分范围
  • 当项目多于属性时,考虑转置表格
  • 将表格与说明文字结合,创建完整且易读的文档

常见问题解答

「请求表格与结构化数据」课时是免费的吗?

是的 — 「请求表格与结构化数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「请求表格与结构化数据」这节课中我会学到什么?

请求使用 Markdown 表格和结构化输出完成比较任务 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「请求表格与结构化数据」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 请求列表与项目符号
  2. 请求表格与结构化数据
  3. 提示中的 Markdown 格式
  4. 纯文本与格式化输出
← 返回 AI Prompt Engineering