ChatGPT 的最佳 Python 用例
ChatGPT 是OpenAI的革命性对话平台,自几个月前发布公开测试版以来,已经风靡全球。基于大型语言模型 (LLM),它能够:
- 回答各种一般性问题
- 针对各种问题提出解决方案
- 就各种学科进行广泛的对话
用户发现 ChatGPT 擅长的学科领域之一是生成编程代码。虽然有很多猜测认为 ChatGPT 将取代程序员甚至改变我们的思维方式,但本博客重点关注该工具今天的实际功能,而不是担心未来的可能性和期望。
在这篇文章中,我将解释 ChatGPT 的代码生成功能,并通过断言关键算法和语义结果将其与行业标准进行比较。我评估 ChatGPT 的标准包括:
- 能够生成正确的代码
- 能够生成有效的代码(即清晰、简洁的代码而不是意大利面条式代码)
- 能够创建可维护的代码(即需要维护的人可以理解的代码)
- 能够生成没有漏洞/安全问题的代码。
这篇文章的主要目的是阐明在现实世界中使用 ChatGPT 的一些好处和注意事项。长话;博士?你得到你所付出的。ChatGPT 代码生成示例让我们看一些简单的 Python 代码示例,其中 ChatGPT 可能会给您一个合理的答案,或者由于不准确而适得其反。
使用 ChatGPT 生成 Python 函数
对于这个例子,我要求 ChatGPT “写一个 Python 函数,从字符串中修剪指定的字符。”
我得到的答案简单明了:
def trim_char(string, char): """ 这个函数接受一个字符串和一个字符,并从字符串的开头和结尾删除该字符的所有实例。 """ return string.strip(char)
- 它还给了我一个例子:
import trim_char my_string = "###Hello World###" char_to_trim = "#" trimmed_string = trim_char(my_string, char_to_trim) print(trimmed_string)
好吧,这非常简单,这正是我们所期望的,因为我要求的东西不仅是微不足道的,而且在 Python 标准库中也可用。让我们尝试一些更高级的东西。
使用 Python 图像库 (PIL) 通过 ChatGPT 生成图像
现在我将要求 ChatGPT “编写一个 Python 函数,使用 Python 图像库 PIL 生成 800 X 600 像素的阴阳符号图像。”
答案是:
from PIL import Image, ImageDraw def generate_yin_yang_image(): # 创建一个白色背景的新图像 image = Image.new("RGB", (800, 600), "white") draw = ImageDraw.Draw(image) # 画出黑色的半圆 draw.pieslice((0, 0, 800, 600), 0, 180, fill="black") # 画出白色的半圆 draw.pieslice((0, 0, 800, 600), 180, 360, fill="white") # 画黑色和白色的圆圈 draw.ellipse((200, 200, 600, 600), fill="white", outline="black") draw.ellipse((200, 0, 600, 400), fill="black", outline="black") # 保存并显示图像 image.save("yin-yang.png") image.show()
图 1:根据 ChatGPT 的阴阳符号结果似乎暗示 ChatGPT 尚未接受过识别图像的训练,因此我不相信它能够承担与视觉世界有联系的编程任务。这里的教训是,在要求它编写代表图形等实体的代码时要非常小心,包括(大概)图表和图形。
使用 Graphene 通过 ChatGPT 生成 GraphQL 名称/路径
让我们要求它“编写代码来查找 GraphQL 解析器名称/路径,而不执行 Python Graphene 中查询的解析器”。
ChatGPT 的答案是:
from graphene import ObjectType, String, Schema class Query(ObjectType): hello = String(name=String(default_value="world")) def resolve_hello(self, info, name): return f"Hello {name}!" schema = Schema(query=Query) # 获取'hello'字段的解析器路径 field_name = 'hello' field = schema.get_query_type().fields[field_name] resolver_path = field.resolver_info.path print(f"The resolver path for '{field_name}' is: {resolver_path}")不幸的是,运行此代码不起作用:
Traceback (most recent call last): File "/Users/theo.despoudis/Workspace/wpe-merge/sink/tempCodeRunnerFile.python", line 1, in <module> field_name NameError: name 'field_name' is not definedGPT 库的实现有两个错误:
- 1. The “Schema” is not the actual GraphQL schema that we want to find the query resolver. We should be using the “graphql_schema” field that contains the schema.
- 2. There is no “get_query_type” method.
实际的代码应该是:
def get_resolver_field(schema, name): return schema.graphql_schema.query_type.fields[name]
metrics = [ { created_at: '2023-3-3T00:00:00.000Z', value: 10000000000, labels: { environment: 'production', storage_type: 'files', }, }, { created_at: '2023-3-4T00:00:00.000Z', value: 50000000000, labels: { environment: 'development', storage_type: 'database', }, }, { created_at: '2023-3-4T00:00:00.000Z', value: 10000000000, labels: { environment: 'staging', storage_type: 'database', }, } ]
- created_at :创建指标的日期。
- value :指标的值。这表示大小(以字节为单位)。
- labels :包含指标元数据的对象。它具有以下属性:
- environment:指标存在的环境。它可以具有三个可能值之一:生产、登台或开发。
- storage_type :此指标值表示的存储类型。它可以具有两个可能值之一:数据库或文件。
该函数应将此对象列表转换为另一个对象,该对象聚合每个“ storage_type”的总数,格式如下:
[ { environmentTotal: { development: 50000000000, production: 0, staging: 10000000000, }, storage_type: 'database', total: 60000000000, }, { environmentTotal: { development: 0, production: 10000000000, staging: 0, }, storage_type: 'files', total: 10000000000, } ]
- storage_type :该聚合值表示的存储类型。
- total:每个环境的值的总和。
- environmentTotal :包含每种环境类型的聚合总计的对象。它有以下子字段:
- development :特定“ storage_type ”的开发环境的总指标值。
- Production :该特定“ storage_type ”的生产环境的总指标值。
- staging :特定“ storage_type ”的暂存环境的总指标值。
您可以使用上面的示例作为输入和预期输出。至此,ChatGPT将会给出更加满意的答案。
下面是一个 Python 函数,它按storage_type标签聚合指标列表:
from collections import defaultdict def aggregate_metrics_by_storage_type(metrics): # 初始化字典以存储聚合值 storage_type_totals = defaultdict(int) environment_totals = defaultdict(lambda: defaultdict(int)) # Iterate through each metric for metric in metrics: # 遍历每个指标 storage_type = metric["labels"]["storage_type"] value = metric["value"] # 增加存储类型和环境的总数 storage_type_totals[storage_type] += value environment_totals[storage_type][metric["labels"].get("environment", "unknown")] += value # 将聚合值转换为所需的格式 results = [] for storage_type, total in storage_type_totals.items(): environment_total = dict(environment_totals[storage_type]) results.append({ "storage_type": storage_type, "total": total, "environmentTotal": environment_total }) return results results = aggregate_metrics_by_storage_type(metrics) print(results)
[{'storage_type': 'files', 'total': 10000000000, 'environmentTotal': {'production': 10000000000}}, {'storage_type': 'database', 'total': 60000000000, 'environmentTotal': {'development': 50000000000, 'staging': 10000000000}}]
- 不太可能感到困惑;更有可能提供更好的代码。
- 具有更大的缓冲区,使您能够在缓冲区溢出并失去上下文、
- 迫使您再次粘贴代码之前与其交互地讨论更大的程序更长时间。
- 响应时间更快。
作为一名经验丰富的软件工程师,我对 ChatGPT 的实际潜力有点怀疑。虽然它不会很快取代人类程序员,但如果使用得当,它可以提高您的工作效率,提高效率并消除错误。只需确保您仅将 ChatGPT 用于学习目的或协助完成不需要人工干预的琐碎任务。