Python字符串split()方法实现拆分片段导出至指定路径的txt和jpg文件
实现方案
前置准备
首先安装生成图片所需的依赖库,执行pip命令即可:pip install pillow
你可以提前自定义txt、jpg文件的存储路径,示例中我用./txt_files和./jpg_files作为演示,替换成你自己的实际路径即可。
完整实现代码
import os from PIL import Image, ImageDraw, ImageFont # 原有拆分逻辑 txt = """This is the first sentence. Then, the second sentence. And at the end, the last sentence.""" x = txt.split(".") # 过滤空片段、去除内容前后多余空格 content_list = [item.strip() for item in x if item.strip()] # 定义存储路径 txt_save_path = "./txt_files" jpg_save_path = "./jpg_files" # 自动创建文件夹,路径已存在也不会报错 os.makedirs(txt_save_path, exist_ok=True) os.makedirs(jpg_save_path, exist_ok=True) # 遍历所有片段逐个导出 for idx, content in enumerate(content_list, start=1): # 导出txt文件 txt_full_path = os.path.join(txt_save_path, f"片段_{idx}.txt") with open(txt_full_path, "w", encoding="utf-8") as f: f.write(content) # 导出jpg文件,将文本内容渲染为图片 # 图片尺寸、背景色、字体字号都可自行调整 img = Image.new("RGB", (800, 200), color="white") draw = ImageDraw.Draw(img) # 优先加载系统自带字体,加载失败则用默认字体 try: font = ImageFont.truetype("arial.ttf", 30) except: font = ImageFont.load_default() draw.text((50, 80), content, font=font, fill="black") jpg_full_path = os.path.join(jpg_save_path, f"片段_{idx}.jpg") img.save(jpg_full_path)
补充说明
- 代码用
os.path.join拼接路径,兼容Windows、Mac、Linux不同系统的路径规则 - 命名规则默认按
片段_1、片段_2递增,可根据需要自行修改 - 生成图片的样式参数可根据实际需求调整,包括图片大小、字体样式、文字位置、颜色等
内容的提问来源于stack exchange,提问作者François
相关产品推荐
相关产品推荐

