Prompts for debugging and reviewing code
输出# Get a list of all files in the folder files = os.listdir(folder_name)
# Iterate over the files for file in files:
# Create a new file name with the prefix "draft_"
new_file_name = f"draft_{file}"
# Move the file to the new name shutil.move(os.path.join(folder_name, file), os.path.join(folder_name, new_file_name))
# Print a success message print("Files renamed successfully.") ```
表 18. 将代码从 Bash 翻译到 Python 的提示
阅读并审查代码。从提示中复制输出内容,粘贴到新文件 file_renamer.py 中。通过打开终端窗口并执行以下命令来测试代码:python file_renamer.py。
注意:在 Ve ex AI 的 Language Studio 中请求( Python)代码时,需点击 ‘Markdown’ 按钮。否则将获得纯文本格式,缺少 Python 代码运行所需的正确行缩进。
调试与代码审查提示
让我们手动对表 18 的代码进行一些编辑。它应提示用户输入文件名前缀,并将该前缀以大写字符形式写入。参见代码片段 *3 的示例,但糟糕的是现在出现了 Python 错误!
Python
import os import shutil
folder_name = input("Enter the folder name: ") prefix = input("Enter the string to prepend to the filename: ") text = toUpperCase(prefix)
if not os.path.isdir(folder_name):
print("Folder does not exist.") exit(1)
files = os.listdir(folder_name)
for file in files:
new_filename = f"{text}_{file}"
shutil.move(os.path.join(folder_name, file), os.path.joi(folder_name, new_file_name))
print("Files renamed successfully.")
Snippet 3. A broken Python script
哎呀!这看起来像是个错误:
The below Python code gives an error:
Traceback (most recent call last):
File “/Users/leeboonstra/Documents/test_folder/rename_files.py”, line 7, in <module> text = toUpperCase(prefix) NameError: name ‘toUpperCase’ is not defined
Snippet 4. I broke the Python code
让我们试试能否让大语言模型来调试和审查代码。请查看表 19:
Name1_python 调试代码
| Goal | 编写一个用于调试和审查Python代码的提示。 |
|---|---|
| 模型 | gemini-pro |
| 温度 | n`x0np 令牌限制 1024 |
Top‑K 采样Top‑P 采样
N/A1 提示词The below Python code gives an error:
Traceback (most recent call last):
File "/ Users/leeboonstra/Documents/test_folder/rename_files.py", line 7, in <module> text = toUpperCase(prefix) NameError: name 'toUpperCase' is not defined
Debug what's wrong and explain how I can improve the code.
```python import os import shutil
# Get the folder name from the user
folder_name = input("Enter the folder name: ") prefix = input("Enter the string to prepend to the filename: ") text = toUpperCase(prefix)
# Check if the folder exists if not os.path.isdir(folder_name):
print("Folder does not exist.") exit(1)
# Get a list of all files in the folder files = os.listdir(folder_name)
# Iterate over the files for file in files:
继续下一页 ...
提示# Create a new file name with the prefix "draft_"
new_filename = f"{text}_{file}"
# Move the file to the new name shutil.move(os.path.join(folder_name, file), os.path.join(folder_name, new_file_name))
# Print a success message print("Files renamed successfully.") ``` 输出代码调用了 `toUpperCase` 函数将 ` 前缀` 转换为大写,但该函数未定义。要解决此问题,可以使用 `upper()` 方法。f 字符串类中的该方法可将给定字符串转换为大写。修改后的代码如下所示:
```python import os import shutil
# Get the folder name from the user folder_name = input("Enter the folder name: ") prefix = input("Enter the string to prepend to the filename: ") text = prefix.upper()
# Check if the folder exists if not os.path.isdir(folder_name):
print("Folder does not exist.") exit(1)
# Get a list of all files in the folder files = os.listdir(folder_name)
# Iterate over the files for file in files:
# Create a new file name with the prefix "draft_"
new_filename = f"{text}_{file}"
# Move the file to the new name shutil.move(os.path.join(folder_name, file),
Continues next page...
输出os.path.join(folder_name, new_filename))
# Print a success message print("Files renamed successfully.") ```
此外,还可以对代码进行一些其他改进:
- 新文件名的扩展名未保留。最好从原文件名中提取扩展名并附加到新文件名上。
- 代码假设文件夹名称中没有空格。然而,最佳实践是通过将空格替换为下划线等方式优雅处理。
- 当前实现未考虑路径中的特殊字符(如中文或符号),建议增加字符编码处理逻辑。
- 可添加异常捕获机制,防止因权限不足或路径不存在导致程序中断。
下划线或连字符。
n•x0~ Using the `f` string syntax for string interpolation is more readable and 比传统的 ŠÀ ‚ ŠÀ ~ 运算符更简洁。
- 代码未处理重命名过程中可能出现的错误x0~
最好将 ŠÀ shutil.moveŠÀ ~ 调用包裹在 ŠÀ try...exceptŠÀ ~ 块中,以捕获任何潜在错误。
以下是应用这些建议后的改进代码:
```python import os import shutil # Get the folder name from the user folder_name = input("Enter the folder name: ") prefix = input("Enter the string to prepend to the filename: ") # Check if the folder exists if not os.path.isdir(folder_name):
print("Folder does not exist.") exit(1) # Get a list of all files in the folder files = os.listdir(folder_name)
# Iterate over the files for file in files:
继续下一页 ...
输出# Get the file extension ext = os.path.splitext(file)[1]
# Create a new file name with the prefix and the file extension new_filename = f"{prefix}_{os.path.splitext(file)[0]}{ext}"
# Build the full paths for the original and new files old_path = os.path.join(folder_name, file) new_path = os.path.join(folder_name, new_filename)
# Try to move the file try:
shutil.move(old_path, new_path)
except Exception as e:
print(f"An error occurred while moving the file {file}: {e}")
# Print a success message print("Files renamed successfully.") ```
These improvements make the code more robust and exible while also making 使其更易于阅读和理解 ...(响应因达到令牌限制而被截断如果需要更长的响应,请尝试增加令牌限制。
更长的回复。
表 19. 用于调试和审查 Python 代码的提示
太棒了。它不仅告诉我如何解决问题,还发现我的代码有更多错误并提供了解决方案。提示的最后部分还给出了改进代码的通用建议。
全站分卷索引 · 34 卷
- 1Introduction
- 2Prompt engineering
- 3LLM output configuration
- 4Sampling controls
- 5Top-K and top-P
- 6Putting it all together
- 7Prompting techniques
- 8One-shot & few-shot
- 9System, contextual and role prompting
- 10System prompting
- 11Role prompting
- 12Contextual prompting
- 13Step-back prompting
- 14Chain of Thought (CoT)
- 15Self-consistency
- 16Tree of Thoughts (ToT)
- 17ReAct (reason & act)
- 18Automatic Prompt Engineering
- 19Code prompting
- 20Prompts for explaining code
- 21Prompts for translating code
- 22Prompts for debugging and reviewing code
- 23What about multimodal prompting?
- 24Design with simplicity
- 25Be specific about the output
- 26Control the max token length
- 27Experiment with input formats and writing styles
- 28Adapt to model updates
- 29JSON Repair
- 30Working with Schemas
- 31Experiment together with other prompt engineers
- 32CoT Best practices
- 33Summary
- 34Endnotes