Python 基础到 AI 实战,我只用了一个案例

24 阅读4分钟

Python 基础到 AI 实战,我只用了一个案例:亚马逊产品文案自动生成

前言

最近在系统学习 Python,从最基础的 list 和切片,到双指针实现字符串 trim,再到大模型 API 调用和 Prompt 工程,一路上踩了不少坑。本文把这些知识点串成一条线,适合刚接触 Python 或想快速上手 LLM 开发的同学。


一、Python List:灵活的动态容器

如果你有 JavaScript 背景,Python 的 list 会让你觉得很亲切——它和 JS 的 Array 非常像:

  • 动态扩容:不需要像 Java/C++ 那样提前指定容量
  • 不约束类型:同一个 list 里可以放不同类型的值
L = ["张三", "李四", "王五", "赵六", "孙七"]

# 取前三项——传统写法
r = []
n = 3
for i in range(n):
    r.append(L[i])

print(r)  # ['张三', '李四', '王五']

但 Python 有更优雅的方式。


二、切片(Slice):一行代码,告别循环

切片是 Python 中最实用的特性之一,大大简化了取部分元素的操作

L = ["张三", "李四", "王五", "赵六", "孙七"]

L[0:3]   # ['张三', '李四', '王五']
L[:3]    # 同上,省略 0
L[1:3]   # ['李四', '王五']
L[-2:]   # ['赵六', '孙七'] —— 倒数两个

切片同样适用于字符串和其他序列类型:

'ABCDEFG'[:3]    # 'ABC'
'ABCDEFG'[::2]   # 'ACEG' —— 步长为2

L = list(range(100))
L[:10]     # 前10个
L[-10:]    # 后10个
L[:10:2]   # 前10个,每隔一个取一个
L[::5]     # 每5个取一个

语法很简单:[start:stop:step],三个值都可以省略,非常灵活。


三、双指针实现 trim:理解切片原理

Python 内置了 strip() 方法,但如果自己实现一个,可以帮助你更好地理解切片和双指针思想:

def trim(s):
    # 左指针:找到第一个非空格字符
    left = 0
    while left < len(s) and s[left] == ' ':
        left += 1

    # 右指针:找到最后一个非空格字符
    right = len(s)
    while right > left and s[right - 1] == ' ':
        right -= 1

    # 切片截取
    return s[left:right]

print(trim("   hello world  "))  # "hello world"

四、LLM 接入:用 DeepSeek API 做产品文案生成

前面都是基础,接下来进入正题——调用大模型 API。

4.1 背景知识

2022 年底,OpenAI 基于 Google 开源的 Transformer 架构,掀起了生成式 AI 浪潮。现在主流大模型厂商包括:

厂商模型API 兼容性
OpenAIGPT 系列行业标准
DeepSeekdeepseek-chat兼容 OpenAI SDK
GoogleGemini有差异
AnthropicClaude有差异

DeepSeek 因为兼容 OpenAI 的 SDK,切换成本极低——只需改 base_urlapi_key

4.2 安装依赖

pip install --upgrade openai -q

4.3 完整代码

from openai import OpenAI

client = OpenAI(
    api_key="你的 DeepSeek API Key",
    base_url="https://api.deepseek.com/v1"
)

COMPLETION_MODEL = "deepseek-chat"

prompt = """
Consideration product:
工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光娃儿童水上玩具
1. Compose human readable product title used on Amazon in english within 20 words.
2. Write 5 selling points for the products in Amazon
3. Evaluate a price range for this product in U.S.

Output the result in json format with three properties called title, selling_point and price_ranges
"""

def get_response(prompt):
    response = client.chat.completions.create(
        model=COMPLETION_MODEL,
        messages=[
            {"role": "user", "content": prompt}
        ]
    )
    return response.choices[0].message.content

result = get_response(prompt)
print(result)

4.4 运行结果

{
  "title": "Inflatable PVC Frog Toy Night Market Best Seller Light Up Water Toys for Kids",
  "selling_point": [
    "Bright LED lights make the frog glow in the dark, perfect for night play and night market atmosphere.",
    "Made of durable PVC material, safe and non-toxic for kids outdoor water fun.",
    "Lightweight and easy to inflate, deflate and carry for pool, beach or bath time.",
    "Eye-catching design and vibrant colors attract children's attention at parties or night markets.",
    "Versatile toy for both land and water activities, including night markets, beaches and swimming pools."
  ],
  "price_ranges": "USD 4.99 - USD 9.99 per piece"
}

五、Prompt 工程要点

以上面的 prompt 为例,一个好的 prompt 需要具备三个要素:

  1. 清晰详细的目标描述:不只是"写个标题",而是"适合 Amazon 的、20 词以内的英文产品标题"
  2. 分步骤:用 1、2、3 编号拆解任务,LLM 更不容易遗漏
  3. 约束输出格式:指定 JSON 格式和字段名(titleselling_pointprice_ranges),方便后续程序解析
Output the result in json format with three properties called title, selling_point and price_ranges

六、为什么 Python 适合这个场景?

回到开头的问题——为什么用 Python 而不是 JS?

  • Python 适合计算:有高精度数值类型,JS 的 Number 类型在处理浮点数时精度有限
  • Python 生态强大:机器学习、爬虫、数据分析的开源库非常丰富
  • JS 适合展示:页面交互、前端渲染是 JS 的主战场

选对工具,事半功倍。


总结

本文从一个简单的 list 切片出发,到双指针实现 trim,最后用 DeepSeek API 完成了一个产品文案生成的实际案例。三个看似独立的知识点,串联起来就是"用 Python 调用 LLM"的完整入门路径。

希望对你有帮助。


本文首发于掘金,作者:dfp