c
1. deepseek 调用方法
1.1. API_KEY设置
设置
URL = "https://deepseek.com/chat/completions/"
导入系统变量,借助
os
os.getenv("变量名称", default = 默认值)
1.2. 请求头
authorization
: Bearer API_KEY, 认证信息Content-Type: application/json
, 请求内容格式,post 仅能使用Json
header = {
"authorization": f"Bearer {API_KEY}"
"Content-Type": "application/json",
}
1.3. 请求内容payload
model
: 选择模型messages
: 发送的内容数组role
:角色content
: 内容
temperature
: 设置为 0 ,模型输出更加稳定, 1,模型输出更发散
payload = {
"model": deepseek-chat,
"messages":[
{"role": "system", "content":"命令要求" },
{"role": "User", "content": "用户输入"},
{"role": ""}
]
}
1.4. 发送请求
发送内容,使用post
请求
resp = requests.post(url, header = header, payload = payload, timeout =timeout)
1.5. response 返回内容
返回内容在resp.json()['choices'][0]['message']['content']
, 提取出结果并返回
2. 翻译
将文本块切分成小段,指定分块大小,存放在数组中
对分段后每一段进行翻译
2.1. for 遍历
for i in 迭代器
迭代器: 列表等
for idx, ck in enumerate(n):
for i in range(1, n) :
范围是[1,n)
3. day3
输入错误:
EOFerror
requests.post
发送请求时,需要包裹在try
中requests
发送数据,解析数据检查检查requests是否接收
except requests.exception.RequestException as e
检查网络是否
resp.ok
数据转换是否成
json
except ValueError
是否可以从数据中提取出值
`except {KeyError, IndexError, TypeError}
3.1. 使用超时重传发送
如果遇到rest
请求错误,或者返回的resq
状态码有问题,使用退避算法,进行规避n
次,超过则返回
- 重复遍历
n
次 - 如果遇到
请求错误
,查看是否超过重复次数,没有,time.sleep
一段时间后,再次运行重传 - 超过重复请求后,返回错误
4. day4
4.1. markdown 渲染
使用rich
库
from rich.console import Console
from rich.markdown import Markdown
console = Console()
markdown_string = """"""
markdown = Markdown(markdown_string)
console
4.2. 输出markdown 到word 文件中
- 首先检查文件目录存在
import os
output_dir = os.path.dirname(output_file)
if output_dir and not os.path.exist(output_dir):
os.makedirs(output_dir)
- 使用
pypandoc
输出
import pypandoc
"""
to: "目标格式"
format:"当前格式"
outputfile: "输出文件"
"""
pypandoc.convert_text(makedown_string, to= 'docx', format = 'markdown', outputfile = output_filepath)
- 同时可以尝试检查
ImportError , Exception
等错误
4.2.1. 直接调用pandoc 命令行工具
创建临时文件.md存储markdown内容
temp_md_file = "temp.md" with open(temp_md_file, 'w', encoding= 'utf-8') as f: f.write(m_str)
使用
subprocess.run
执行命令import subprocess command = ['pandoc', '-f', 'markdown', 't','doc', 'o', output_filename, temp_md_file] result = subprocess.run(command, capture_output = True, text = True, encoding = 'utf-8') if result.returncode == 0: return "转换正确"
最后删除临时文件
if os.path.exist(temp_md_file): os.remove(temp_md_file)
5. 9.8
win11 主要文件夹路径
任务栏:C:\Users\用户名\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar
开始菜单:C:\ProgramData\Microsoft\Windows\Start Menu\Programs
IE开始菜单C:\Users\用户名\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu
6. 9.10
6.1. path类
from pathlib import Path
p_path = Path(路径)
# 组合路径
config_path = p_path / "config.txt"
.name # 文件名
.suffix # 文件后缀
.stem # 无后缀的文件名
.parent # 父目录
.is_absolute # 是否为祖先路径
.revolve() # 转换为相对路径
# 创建文件
# parents=True 会创建所有不存在的父目录
# exist_ok=True 避免目录已存在时报错
Path(路径).mkdir(exist_ok = True, parents = True)
Path(路径).touch() # 创建空文件
p_path.write_text(str) # 写入文件
content = file.read_text() # 读取文件内容