跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像AI 生图工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
PythonAI算法

面向 AI 学习者的 Python 快速入门指南

面向已有编程基础但熟悉度较低的读者,介绍 Python 在 AI 开发中的快速入门。内容涵盖 Python 安装、数据类型(字符串、数字、列表、字典)、变量、脚本创建、循环与条件语句、函数定义以及库管理(pip、venv)。最后通过一个从 PDF 提取摘要并调用 OpenAI API 生成关键词的示例项目,演示了如何结合基础语法与外部库完成简单的 AI 任务。

赛博朋克发布于 2026/3/15更新于 2026/6/3040 浏览

Python QuickStart for People Learning AI

Python 已经成为 AI 和数据科学的默认编程语言。尽管存在无代码解决方案,但学习如何编码仍然是构建完全定制的 AI 项目和产品所必需的。在这篇文章中,我分享了一个 Python AI 开发的入门级快速入门指南。我将介绍基础知识,然后分享一个具体的示例代码。

Python是一种编程语言,即一种向计算机提供精确指令以完成我们无法或不想做的事情的方式。

当需要自动化一个没有现成解决方案的独特任务时,这很有用。例如,如果我想自动化撰写和发送个性化的会议后续跟进,我可以编写一个 Python 脚本来完成这项任务。

使用 ChatGPT 等工具,我们可以想象一个未来,在那里人们可以用普通的英语描述任何定制任务,而计算机就会完成它。然而,这样的消费级产品目前还不存在。在这样产品出现之前,了解(至少是稍微了解)Python 具有巨大的价值。

编码比以往任何时候都要容易

尽管当前的 AI 产品(例如 ChatGPT、Claude、Gemini)还没有使编程变得过时(至少目前还没有),但它们让学习如何编程变得比以往任何时候都要容易。我们现在都有一个称职且耐心的编码助手,他随时准备帮助我们学习。

结合'传统'的 Google 搜索问题解决方案,程序员现在可以更快地工作。例如,我慷慨地使用 ChatGPT 来编写示例代码和解释错误信息。这加速了我的进度,并在导航新技术堆栈时给了我更多的信心。

本指南面向对象

我写这篇文章时考虑的是特定类型的读者:那些试图进入 AI 领域并且已经进行过一些编码(例如,JS、HTML/CSS、PHP、Java、SQL、Bash/Powershell、VBA)但对 Python 却不太熟悉的人。

我将从 Python 基础知识开始,然后分享一个简单 AI 项目的示例代码。这不是一个全面的 Python 入门介绍。相反,它的目的是让你能够快速用 Python 编写你的第一个 AI 项目。

安装 Python

许多计算机都预装了 Python。要查看您的机器是否安装了它,请转到您的终端(Mac/Linux)或命令提示符(Windows),然后简单地输入'python'。

如果您没有看到这样的屏幕,您可以手动下载 Python(Windows/Mac)。或者,可以安装 Anaconda,这是一个流行的 Python 包系统,用于 AI 和数据科学。如果您遇到安装问题,请向您的首选 AI 助手寻求帮助!

当 Python 运行时,我们现在可以开始编写一些代码。我建议我们在学习过程中在你的电脑上运行这些示例。你还可以从 GitHub 仓库下载所有示例代码。

1) 数据类型

字符串与数字

数据类型(或简称'类型')是一种对数据进行分类的方法,以便在计算机中适当地高效地处理。

类型由可能的一组值和操作定义。例如,字符串是任意字符序列(即文本),可以通过特定方式操作。尝试在您的命令行 Python 实例中输入以下字符串。

"this is a string"
# 'this is a string'

'so is this:-1*!@&04"(*&^}":>?' 
# 'so is this:-1*!@&04"(*&^}":>?'

"""and this is too!!11!"""
# 'andn this isn too!!11!'

"we can even " + "add strings together"
# 'we can even add strings together'

尽管字符串可以连接(即连接),但它们不能与数值数据类型(如int(即整数)或 float(即带小数的数字))相加。如果我们尝试在 Python 中这样做,我们将得到一个错误消息,因为操作仅定义在兼容类型上。

# we can't add strings to other data types (BTW this is how you write comments in Python)
"I am " + 29
# TypeError: can only concatenate str(not"int") to str

# so we have to write 29 as a string
"I am " + "29"
# 'I am 29'

列表与字典

除了基本的字符串、整数和浮点数类型之外,Python 还有用于结构化更大数据集合的类型。

其中一种类型是列表,一个有序的值集合。我们可以有字符串列表、数字列表、字符串 + 数字列表,甚至是列表的列表。

# a list of strings
["a", "b", "c"]
# a list of ints
[1, 2, 3]
# list with a string, int, and float
["a", 2, 3.14]
# a list of lists
[["a", "b"], [1, 2], [1.0, 2.0]]

另一个核心数据类型是字典,它由键值对序列组成,其中键是字符串,值可以是任何数据类型。这是表示具有多个属性的数据的绝佳方式。

# a dictionary
{"Name": "Shaw"}
# a dictionary with multiple key-value pairs
{"Name": "Shaw", "Age": 29, "Interests": ["AI", "Music", "Bread"]}
# a list of dictionaries
[{"Name": "Shaw", "Age": 29, "Interests": ["AI", "Music", "Bread"]}, {"Name": "Ify", "Age": 27, "Interests": ["Marketing", "YouTube", "Shopping"]}]
# a nested dictionary
{"User": {"Name": "Shaw", "Age": 29, "Interests": ["AI", "Music", "Bread"]}, "Last_login": "2024-09-06", "Membership_Tier": "Free"}

2) 变量

到目前为止,我们已经看到了一些基本的 Python 数据类型和操作。然而,我们仍然缺少一个基本功能:变量。

变量提供对底层数据类型实例的抽象表示。例如,我可能创建一个名为 user_name 的变量,它代表一个包含我的名字'Shaw'的字符串。这使得我们能够编写灵活的程序,而不会局限于特定的值。

# creating a variable and printing it
user_name = "Shaw"
print(user_name)
#>> Shaw

我们可以用其他数据类型做同样的事情,例如整数和列表。

# defining more variables and printing them as a formatted string.
user_age = 29
user_interests = ["AI", "Music", "Bread"]
print(f"{user_name} is {user_age} years old. His interests include {user_interests}.")
#>> Shaw is 29 years old. His interests include ['AI', 'Music', 'Bread']. 

3) 创建脚本

现在我们示例代码片段越来越长,让我们看看如何创建我们的第一个脚本。这就是我们从命令行 编写和执行更复杂的程序 的方法。

要做到这一点,请在您的计算机上创建一个新的文件夹。我将其命名为 python-quickstart。如果您有一个喜欢的 IDE(例如,集成开发环境),请使用它来打开这个新文件夹并创建一个新的 Python 文件,例如,my-script.py。在那里,我们可以编写仪式性的'Hello, world'程序。

# ceremonial first program
print("Hello, world!")

如果您没有 IDE(不推荐),您可以使用基本的文本编辑器(例如,苹果的 TextEdit,Windows 的记事本)。在这些情况下,您可以通过使用 .py 扩展名而不是 .txt 来打开文本编辑器并保存一个新的文本文件。注意:如果您在 Mac 上使用 TextEditor,可能需要通过格式 > 制作纯文本将应用程序置于纯文本模式。

然后,我们可以通过导航到包含我们新 Python 文件的文件夹并运行以下命令来使用终端(Mac/Linux)或命令提示符(Windows)运行此脚本。

python my-script.py

恭喜!您运行了您的第一个 Python 脚本。您可以随意 通过复制粘贴即将出现的代码示例并重新运行脚本来扩展此程序,以查看它们的输出。

4) 循环和条件

Python(或任何其他编程语言)的两个基本功能是循环和条件。

循环允许我们 多次运行特定的代码块。最受欢迎的是 for 循环,它在迭代变量时运行相同的代码。

# a simple for loop iterating over a sequence of numbers
for i in range(5):
    print(i) # print ith element

# for loop iterating over a list
user_interests = ["AI", "Music", "Bread"]
for interest in user_interests:
    print(interest) # print each item in list

# for loop iterating over items in a dictionary
user_dict = {"Name": "Shaw", "Age": 29, "Interests": ["AI", "Music", "Bread"]}
for key, value in user_dict.items():
    print(key, "=", value) # print each key and corresponding value

另一个核心功能是 条件,例如 if-else 语句,它 使我们能够编写逻辑。例如,我们可能想要检查用户是否为成年人或评估他们的智慧。

# check if user is 18 or older
if user_dict["Age"] >= 18:
    print("User is an adult")

# check if user is 1000 or older, if not print they have much to learn
if user_dict["Age"] >= 1000:
    print("User is wise")
else:
    print("User has much to learn")

在 for 循环中使用条件是常见的,可以根据特定条件应用不同的操作,例如计算对面包感兴趣的用户数量。

# count the number of users interested in bread
user_list = [
    {"Name": "Shaw", "Age": 29, "Interests": ["AI", "Music", "Bread"]},
    {"Name": "Ify", "Age": 27, "Interests": ["Marketing", "YouTube", "Shopping"]}
]
count = 0 # intialize count
for user in user_list:
    if "Bread" in user["Interests"]:
        count = count + 1 # update count
print(count, "user(s) interested in Bread")

5) 函数

函数是我们可以在特定数据类型上执行的 操作。

我们已经看到了一个基本函数 print(),它为任何数据类型定义。然而,还有一些其他值得了解的实用函数。

# print(), a function we've used several times already
for key in user_dict.keys():
    print(key, ":", user_dict[key])

# type(), getting the data type of a variable
for key in user_dict.keys():
    print(key, ":", type(user_dict[key]))

# len(), getting the length of a variable
for key in user_dict.keys():
    print(key, ":", len(user_dict[key]))
    # TypeError: object of type 'int' has no len()

我们可以看到,与 print() 和 type() 不同,len() 并不是为所有数据类型定义的,所以当它应用于一个整数时,会抛出一个错误。还有其他几个这样的 类型特定函数。

# string methods
# make string all lowercase
print(user_dict["Name"].lower())
# make string all uppercase
print(user_dict["Name"].upper())
# split string into list based on a specific character sequence
print(user_dict["Name"].split("ha"))
# replace a character sequence with another
print(user_dict["Name"].replace("w", "whin"))
# list methods
# add an element to the end of a list
user_dict["Interests"].append("Entrepreneurship")
print(user_dict["Interests"])
# remove a specific element from a list
user_dict["Interests"].pop(0)
print(user_dict["Interests"])
# insert an element into a specific place in a list
user_dict["Interests"].insert(1, "AI")
print(user_dict["Interests"])
# dict methods
# accessing dict keys
print(user_dict.keys())
# accessing dict values
print(user_dict.values())
# accessing dict items
print(user_dict.items())
# removing a key
user_dict.pop("Name")
print(user_dict.items())
# adding a key
user_dict["Name"] = "Shaw"
print(user_dict.items())

虽然核心 Python 函数很有帮助,但真正的力量来自于创建 用户定义函数 来 执行自定义操作。此外,自定义函数允许我们编写更干净的代码。例如,以下是一些以前代码片段重新打包为用户定义函数。

# define a custom function
def user_description(user_dict):
    """ Function to return a sentence (string) describing input user """
    return f'{user_dict["Name"]} is {user_dict["Age"]} years old and is interested in {user_dict["Interests"][0]}.'

# print user description
description = user_description(user_dict)
print(description)

# print description for a new user!
new_user_dict = {"Name": "Ify", "Age": 27, "Interests": ["Marketing", "YouTube", "Shopping"]}
print(user_description(new_user_dict))
# define another custom function
def interested_user_count(user_list, topic):
    """ Function to count number of users interested in an arbitrary topic """
    count = 0
    for user in user_list:
        if topic in user["Interests"]:
            count = count + 1
    return count

# define user list and topic
user_list = [user_dict, new_user_dict]
topic = "Shopping"

# compute interested user count and print it
count = interested_user_count(user_list, topic)
print(f"{count} user(s) interested in {topic}")

6) 库,pip,& venv

尽管我们可以使用核心 Python 实现任意程序,但对于某些用例来说,这可能会非常耗时。Python 的一个关键优势是其 充满活力的开发者社区和强大的软件包生态系统。您可能想要用核心 Python 实现的大部分内容(可能)已经作为开源库存在。

我们可以使用 Python 的原生包管理器 pip 安装这样的包。要安装新包,我们从命令行运行 pip 命令。以下是如何安装 numpy 的示例,这是一个实现基本数学对象和操作的基本数据科学库。

pip install numpy

在我们安装了 numpy 之后,我们可以将其导入到一个新的 Python 脚本中,并使用它的一些数据类型和函数。

import numpy as np

# create a "vector"
v = np.array([1, 3, 6])
print(v)

# multiply a "vector"
print(2*v)

# create a matrix
X = np.array([v, 2*v, v/2])
print(X)

# matrix multiplication
print(np.matmul(X, v))

之前的 pip 命令将 numpy 添加到了我们的基础 Python 环境中。或者,创建所谓的 虚拟环境 是一种最佳实践。这些是 可以轻松互换用于不同项目的 Python 库集合。

这是创建名为 my-env 的新虚拟环境的方法。

python -m venv my-env

然后,我们可以激活它。

# mac/linux
source my-env/bin/activate
# windows
my-env\Scripts\activate.bat

最后,我们可以使用 pip 安装新的库,例如 numpy。

pip install numpy

注意:如果您使用的是 Anaconda,请查看创建新 conda 环境的实用速查表。

在人工智能和数据科学中,还有许多其他库被广泛使用。以下是构建 AI 项目的一些有用的库的非全面概述。

示例代码:从研究论文中提取摘要和关键词

既然我们已经接触到了 Python 的基础知识,让我们看看如何用它来实现一个简单的 AI 项目。在这里,我将使用 OpenAI API 来创建一个研究论文摘要器和关键词提取器。

与本指南中的其他所有代码片段一样,示例代码可在 GitHub 仓库中找到。

安装依赖

我们首先安装一些有用的库。您可以使用我们之前创建的相同 my-env 环境,或者创建一个新的环境。然后,您可以使用 requirements.txt 文件安装所有必需的包。

pip install -r requirements.txt

这行代码会扫描 requirements.txt 中列出的每个库,并安装它们。

导入

接下来,我们可以创建一个新的 Python 脚本并导入所需的库。

import fitz # PyMuPDF
import openai
import sys

接下来,为了使用 OpenAI 的 Python API,我们需要导入一个 AI 密钥。这里有一种实现方式。

from sk import my_sk # Set up your OpenAI API key
openai.api_key = my_sk

注意,sk 不是一个 Python 库。相反,它是一个单独的 Python 脚本,它定义了一个变量,my_sk,这是一个 由我的 OpenAI API 密钥组成的字符串,即一个唯一的(且秘密的)令牌,允许使用 OpenAI 的 API。

我在上一篇文章中分享了一个关于 API、OpenAI API 以及设置 API 密钥的入门介绍。

读取 PDF

接下来,我们将创建一个函数,给定保存为 .pdf 文件的论文路径,将从中提取摘要。

# Function to read the first page of a PDF and extract the abstract
def extract_abstract(pdf_path):
    # Open the PDF file and grab text from the 1st page
    with fitz.open(pdf_path) as pdf:
        first_page = pdf[0]
        text = first_page.get_text("text")
    
    # Extract the abstract (assuming the abstract starts with 'Abstract')
    # find where abstract starts
    start_idx = text.lower().find('abstract')
    
    # end abstract at introduction if it exists on 1st page
    if 'introduction' in text.lower():
        end_idx = text.lower().find('introduction')
    else:
        end_idx = None
    
    # extract abstract text
    abstract = text[start_idx:end_idx].strip()
    
    # if abstract appears on 1st page return it, if not resturn None
    if start_idx != -1:
        abstract = text[start_idx:end_idx].strip()
        return abstract
    else:
        return None

使用 LLM 概述

现在我们有了摘要文本,我们可以使用 LLM 来总结它并生成关键词。在这里,我定义了一个函数,将摘要传递给 OpenAI 的 GPT-4o-mini 模型来完成这项工作。

# Function to summarize the abstract and generate keywords using OpenAI API
def summarize_and_generate_keywords(abstract):
    # Use OpenAI Chat Completions API to summarize and generate keywords
    prompt = f"Summarize the following paper abstract and generate (no more than 5) keywords:\n\n{abstract}"
    
    # make api call
    response = openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": prompt}
        ],
        temperature = 0.25
    )
    
    # extract response summary
    summary = response.choices[0].message.content
    return summary

将所有内容整合在一起

最后,我们可以使用我们定义的用户函数为任何通过命令行传递给程序的论文生成摘要和关键词。

# Get the PDF path from the command-line arguments
pdf_path = sys.argv[1]

# Extract abstract from the PDF
abstract = extract_abstract(pdf_path)

# if abstract exists on first page, print summary.
if abstract:
    # Summarize and generate keywords
    summary = summarize_and_generate_keywords(abstract)
    print(summary)
else:
    print("Abstract not found on the first page.")

然后,我们可以从命令行执行我们的程序。

python summarize-paper.py "files/attention-is-all-you-need.pdf"
Output: The paper introduces the Transformer, a novel network architecture for sequence transduction tasks that relies solely on attention mechanisms, eliminating the need for recurrent and convolutional structures. The Transformer demonstrates superior performance in machine translation tasks, achieving a BLEU score of 28.4 on the WMT 2014 English-to-German translation and a state-of-the-art score of 41.8 on the English-to-French translation task,while also being more efficient in training time. Additionally, the Transformer shows versatility by successfully applying to English constituency parsing with varying amounts of training data.**Keywords:** Transformer, attention mechanisms, machine translation, BLEU score, neural networks.

接下来是什么?

在这里,我们涵盖了 Python 的基础知识并实现了我们的第一个 AI 项目!尽管我们已经覆盖了很多内容,但还有更多要学习。

下一步是实施你自己的 AI 项目。这是持续学习的最佳方式。然而,在我们继续之前,这里有一些提示。

  • 在遇到困难时,请慷慨地使用 Google 和 ChatGPT
  • '弄懂它' 是作为程序员必须培养的关键技能
  • 查看数据科学家最喜欢的工具:Jupyter Notebooks
  • 从本指南的示例中破解以开始!

目录

  1. Python QuickStart for People Learning AI
  2. 编码比以往任何时候都要容易
  3. 本指南面向对象
  4. 安装 Python
  5. 1) 数据类型
  6. 字符串与数字
  7. 'this is a string'
  8. 'so is this:-1!@&04"(&^}":>?'
  9. 'andn this isn too!!11!'
  10. 'we can even add strings together'
  11. we can't add strings to other data types (BTW this is how you write comments in Python)
  12. TypeError: can only concatenate str(not"int") to str
  13. so we have to write 29 as a string
  14. 'I am 29'
  15. 列表与字典
  16. a list of strings
  17. a list of ints
  18. list with a string, int, and float
  19. a list of lists
  20. a dictionary
  21. a dictionary with multiple key-value pairs
  22. a list of dictionaries
  23. a nested dictionary
  24. 2) 变量
  25. creating a variable and printing it
  26. defining more variables and printing them as a formatted string.
  27. 3) 创建脚本
  28. ceremonial first program
  29. 4) 循环和条件
  30. a simple for loop iterating over a sequence of numbers
  31. for loop iterating over a list
  32. for loop iterating over items in a dictionary
  33. check if user is 18 or older
  34. check if user is 1000 or older, if not print they have much to learn
  35. count the number of users interested in bread
  36. 5) 函数
  37. print(), a function we've used several times already
  38. type(), getting the data type of a variable
  39. len(), getting the length of a variable
  40. string methods
  41. make string all lowercase
  42. make string all uppercase
  43. split string into list based on a specific character sequence
  44. replace a character sequence with another
  45. list methods
  46. add an element to the end of a list
  47. remove a specific element from a list
  48. insert an element into a specific place in a list
  49. dict methods
  50. accessing dict keys
  51. accessing dict values
  52. accessing dict items
  53. removing a key
  54. adding a key
  55. define a custom function
  56. print user description
  57. print description for a new user!
  58. define another custom function
  59. define user list and topic
  60. compute interested user count and print it
  61. 6) 库,pip,& venv
  62. create a "vector"
  63. multiply a "vector"
  64. create a matrix
  65. matrix multiplication
  66. mac/linux
  67. windows
  68. 示例代码:从研究论文中提取摘要和关键词
  69. 安装依赖
  70. 导入
  71. 读取 PDF
  72. Function to read the first page of a PDF and extract the abstract
  73. 使用 LLM 概述
  74. Function to summarize the abstract and generate keywords using OpenAI API
  75. 将所有内容整合在一起
  76. Get the PDF path from the command-line arguments
  77. Extract abstract from the PDF
  78. if abstract exists on first page, print summary.
  79. 接下来是什么?
  • 免费图片AI生成工具免费生成了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 免费图片视频在线生成30秒,将你的创意变成现实开始设计
  • X/Twitter免费视频下载器免登陆无限额度免费视频解析下载了解详情
  • 100+免费在线小游戏爽一把
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • 数据稀疏场景下 Embedding 学习策略综述
  • Web 安全学习笔记:网络协议、漏洞攻防与内网渗透指南
  • Java 线程池核心机制与调度原理
  • Python ASGI 服务器 uvicorn 极简实战指南
  • Claude Code 源码因 Source Map 泄露事件复盘,Anthropic 发布流程失误分析
  • C++ 虚函数深度解析:多态、语法与底层原理
  • SmolVLA 高算力适配:TensorRT 加速可行性分析与 ONNX 导出实操
  • Gephi 网络布局算法详解
  • C++ string 类进阶:成员函数与全局操作实战指南
  • 单机多节点搭建 RabbitMQ 集群详解
  • 二分查找算法详解与经典例题解析
  • Android WebView 版本升级方案详解
  • Android 面试核心考点与实战经验总结
  • OpenClaw 接入 QQ Bot 指南:AI 助手入驻 QQ
  • Windows 11 安装 GitHub Spec Kit 工具包及核心解读
  • Shannon:AI 驱动 Web 应用自动化渗透测试工具
  • Python 快速入门:基础语法与实战
  • CentOS 7 安装 JDK 1.8 及解决 wget 命令缺失问题
  • AIGC 时代的核心协议:深入理解 Model Context Protocol (MCP)
  • 大模型基础概念、发展历程及应用场景详解

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • RSA密钥对生成器

    生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online

  • Mermaid 预览与可视化编辑

    基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online

  • 随机西班牙地址生成器

    随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • curl 转代码

    解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online