案例一
前情提要:我有一个700多文档的文件夹,然后需要编写博客,如果我一个一个抄写到博客里面很麻烦,于是我想着可不可以写一个Python脚本,获取当前目录下的所有文件,然后依次遍历,把文件名交给本地大模型,让它返回我所需要的格式(格式要求在代码中),最好整理成一篇文章,于是就有了下面的两个案例。
获取当前目录下的所有文件(排除脚本自身)。
逐个把文件名传给 ollama 本地模型 qwen2.5:7b。
指定 prompt,让模型 严格输出你需要的格式 :
1 2 ##文件名 [文件名](https://raw.githubusercontent.com/Cherises/Blog-Resource/main/file/各行业工作总结大全734份/文件名)
把每次结果打印到终端,并最终写入一个 output.md 文件。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 import osimport subprocessfrom tqdm import tqdm def call_ollama (model: str , prompt: str ) -> str : """ 调用本地 ollama 模型,返回生成的结果 """ try : result = subprocess.run( ["ollama" , "run" , model], input =prompt, capture_output=True , text=True , encoding="utf-8" , errors="ignore" , check=True ) return result.stdout.strip() if result.stdout else "" except subprocess.CalledProcessError as e: print (f"❌ 调用 ollama 出错: {e.stderr} " ) return "" def main (): model = "qwen2.5:7b" output_file = "output.md" all_files = [f for f in os.listdir("." ) if os.path.isfile(f)] script_name = os.path.basename(__file__) all_files = [f for f in all_files if f not in [script_name, output_file]] results = [] for idx, filename in enumerate (tqdm(all_files, desc="处理中" , unit="file" ), 1 ): prompt = f"""你现在的任务是根据文件名生成严格指定格式的Markdown。 文件名是:{filename} 严格输出以下格式(不要添加任何额外文字): ##{filename} [{filename} ](https://raw.githubusercontent.com/Cherises/Blog-Resource/main/file/各行业工作总结大全734份/{filename} ) """ print (f"\n===== 正在处理第 {idx} /{len (all_files)} 个文件: {filename} =====" ) result = call_ollama(model, prompt) if result: print (result) results.append(result) with open (output_file, "w" , encoding="utf-8" ) as f: f.write("\n\n" .join(results)) print (f"\n✅ 已完成,结果保存到 {output_file} " ) if __name__ == "__main__" : main()
🚀 关键改动:
input=prompt(不用 .encode())。
保留 text=True, encoding="utf-8", errors="ignore" 来确保不会乱码。
用 tqdm 显示总进度(比如 734/734)。
案例二 在案例一基础上修改,让它根据文件类型判断输出格式(图片 vs 其他文件),然后循环处理目录下所有文件,并把每条结果打印到终端,最终生成 Markdown 文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 import osimport subprocessfrom tqdm import tqdm IMAGE_EXTENSIONS = {".png" , ".jpg" , ".jpeg" , ".gif" , ".bmp" , ".webp" } def call_ollama (model: str , prompt: str ) -> str : """ 调用本地 ollama 模型,返回生成的结果 """ try : result = subprocess.run( ["ollama" , "run" , model], input =prompt, capture_output=True , text=True , encoding="utf-8" , errors="ignore" , check=True ) return result.stdout.strip() if result.stdout else "" except subprocess.CalledProcessError as e: print (f"❌ 调用 ollama 出错: {e.stderr} " ) return "" def generate_prompt (filename: str ) -> str : """ 根据文件名生成 ollama 提示 """ ext = os.path.splitext(filename)[1 ].lower() if ext in IMAGE_EXTENSIONS: prompt = f"""你现在的任务是根据文件名生成严格指定格式的Markdown。 文件名是:{filename} 严格输出以下格式(不要添加任何额外文字): ## {filename}  """ else : prompt = f"""你现在的任务是根据文件名生成严格指定格式的Markdown。 文件名是:{filename} 严格输出以下格式(不要添加任何额外文字): ## {filename} [{filename} ](https://raw.githubusercontent.com/Cherises/Blog-Resource/main/file/各行各业运营知识地图/{filename} ) """ return prompt def main (): model = "qwen2.5:7b" output_file = "output.md" all_files = [f for f in os.listdir("." ) if os.path.isfile(f)] script_name = os.path.basename(__file__) all_files = [f for f in all_files if f not in [script_name, output_file]] results = [] for idx, filename in enumerate (tqdm(all_files, desc="处理中" , unit="file" ), 1 ): prompt = generate_prompt(filename) print (f"\n===== 正在处理第 {idx} /{len (all_files)} 个文件: {filename} =====" ) result = call_ollama(model, prompt) if result: print (result) results.append(result) with open (output_file, "w" , encoding="utf-8" ) as f: f.write("\n\n" .join(results)) print (f"\n✅ 已完成,结果保存到 {output_file} " ) if __name__ == "__main__" : main()
✅ 修改点说明 :
增加 IMAGE_EXTENSIONS 集合,用来判断文件是否为图片。
generate_prompt 函数根据文件扩展名生成不同 Markdown 格式的 prompt。
调用 ollama 时直接用生成好的 prompt。
每次处理的结果都会打印到终端,方便查看进度。
支持 300+ 文件循环,最终输出 output.md。