在上面代码的基础上,添加进度条
时间: 2024-03-18 11:39:14 浏览: 24
要在程序中添加进度条,可以使用tqdm库。这个库可以方便地为循环添加进度条,让程序更加直观和友好。
首先,需要安装tqdm库。可以使用pip命令进行安装:
```
pip install tqdm
```
安装完成后,在程序中导入tqdm:
```python
from tqdm import tqdm
```
然后,在循环中使用tqdm函数,将需要迭代的对象传给它即可自动添加进度条。例如,在上面的代码中,可以这样修改:
```python
import openai
from prompt_toolkit import prompt
from tqdm import tqdm
# 设置CSDN API密钥
openai.api_key = "YOUR_API_KEY_HERE"
# 设置对话模型的引擎ID
model_engine = "davinci"
# 设置对话模型的ID
model_id = "YOUR_MODEL_ID_HERE"
# 设置对话的起始文本
start_text = "你好,我叫小G,请问有什么可以帮助您?"
# 开始对话
response = start_text
while True:
# 获取用户输入
user_input = prompt(response + "\n")
# 判断用户是否输入了退出命令
if user_input.lower() in ["退出", "再见", "拜拜", "88"]:
break
# 调用CSDN API进行对话
with tqdm(total=100, desc="正在思考", bar_format="{desc}: {percentage:3.0f}%|{bar}|") as pbar:
response = openai.Completion.create(
engine=model_engine,
prompt=response + user_input,
temperature=0.5,
max_tokens=1024,
n=1,
stop=None,
).choices[0].text.strip()
pbar.update(100)
print(response)
```
这样,在每次调用CSDN API时,都会显示一个进度条,表示程序正在进行。进度条的样式可以通过bar_format参数进行自定义。这个参数是一个字符串,其中包含一些格式化符号,例如`{desc}`表示进度条的描述,`{percentage:3.0f}`表示百分比,`{bar}`表示进度条本身。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)