当前位置: 首页 > news >正文

python + word

将一个文件夹的文本合并

电脑中的一个文件夹中的word文件有多个,想要合并这些文件。

代码如下:

import docx import os from docx import Document#创建document对象,即打开一个word 文档 mydocument=Document() myp=mydocument.add_paragraph(" ") os.chdir("E:\【实践】FutureOfMyLife\【博士】中期考核\【★】真题及模拟") subList=os.listdir(os.getcwd())#总的eng文件夹。 for idocx in subList: mydocument.add_heading(f"文章{idocx}",level=0) ifile=docx.Document(f"{idocx}")#使用docx包读取文件 for p in ifile.paragraphs: line=p.text myp.add_run(line)#把段落添加入文件 myp.add_run("\n") mydocument.save("resulteng.docx")

但是,这些文件原有的格式失去了。是以txt字符的形式合并到了docx文件中。

代码需要优化。合并多个.docx文件并保留原始格式(如加粗、字号、空格等)

优化代码如下:

import os from docx import Document from docx.shared import Pt from docx.enum.text import WD_ALIGN_PARAGRAPH def merge_docx_files(folder_path, output_path): merged_doc = Document() for filename in os.listdir(folder_path): if filename.endswith(".docx"): file_path = os.path.join(folder_path, filename) sub_doc = Document(file_path) # 可选:添加文件名作为标题 merged_doc.add_heading(filename, level=1) for para in sub_doc.paragraphs: new_para = merged_doc.add_paragraph() copy_paragraph_format(para, new_para) # 添加分页符(可选) merged_doc.add_page_break() merged_doc.save(output_path) print(f"合并完成,输出文件:{output_path}") def copy_paragraph_format(source_para, target_para): # 复制段落格式 target_para.alignment = source_para.alignment target_para.style = source_para.style for run in source_para.runs: new_run = target_para.add_run(run.text) copy_run_format(run, new_run) def copy_run_format(source_run, target_run): # 复制字体格式 target_run.bold = source_run.bold target_run.italic = source_run.italic target_run.underline = source_run.underline target_run.font.name = source_run.font.name if source_run.font.size: target_run.font.size = source_run.font.size # 使用示例 folder_path = r"E:\【实践】FutureOfMyLife\【博士】中期考核\【★】真题及模拟" output_path = r"E:\【实践】FutureOfMyLife\【博士】中期考核\【★】真题及模拟\合并结果.docx" merge_docx_files(folder_path, output_path)

即可完成。

将多个文件夹的文本合并

首先运用os模块获得多个文本的名称。然后,运用相关包读取这些文件,并汇集在一起。

运用函数安装包:os

将百度网盘中的文件下载在电脑上

以下载后的eng文件夹为例,eng文件夹中包含很多子文件夹。

将多份在百度网盘中的word文件,合并在一起。代码如下:

import docx import os wfile=open("result.txt","w",encoding="utf-8") os.chdir("E:\eng") subList=os.listdir(os.getcwd())#总的eng文件夹。 for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) for idocx in inumList: print(f"文章{idocx}",file=wfile) ifile=docx.Document(f"{idocx}") for p in ifile.paragraphs: line=p.text print(line,file=wfile) print("\n",file=wfile) wfile.close()

解析如下:

第一步,和程序文件放在一起(以test.py为例)。

import os os.chdir("E:\eng") subList=os.listdir(os.getcwd())#总的eng文件夹。 for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) print(inumList)

第二步,打开程序包docx,如果没有安装,就用pip安装

pip install python-docx

然后会显示安装成功。

第三步,调用docx包去读取docx文件。

for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) for idocx in inumList: print(f"文章{idocx}",file=wfile)#便于区分各个文件 ifile=docx.Document(f"{idocx}")#使用docx包读取文件 for p in ifile.paragraphs: line=p.text print(line,file=wfile)#把文件输入wfile文档中 print("\n",file=wfile)

第四步,最后把生成的txt文本,复制粘贴到docx文本中,就可以完成。

当然,可以将代码进一步优化。比如,用docx包生成word,而不是生成txt。如下:

import docx import os from docx import Document#创建document对象,即打开一个word 文档 mydocument=Document() myp=mydocument.add_paragraph(" ") os.chdir("E:\eng") subList=os.listdir(os.getcwd())#总的eng文件夹。 for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) for idocx in inumList: mydocument.add_heading(f"文章{idocx}",level=0) ifile=docx.Document(f"{idocx}")#使用docx包读取文件 for p in ifile.paragraphs: line=p.text myp.add_run(line)#把段落添加入文件 myp.add_run("\n") mydocument.save("resulteng.docx")

但是在实践过程中,这段代码没有成功。优化功能没有实现。之后需要补充docx包相关的知识,然后去解决这个问题。

整理文本目录

利用豆包或者Kimi生成书籍的目录。

将其复制到word中,出现一个问题,各个章是分开的,但是各个小节的标题是合并在一起的。

在python中,如何按照1.1,3.1,20.1,20.2等类似的小节序号,将其分段?

首先尝试用正则表达式。代码如下:

file=open("content.txt","r",encoding="utf-8") data=file.read() file.close() import re def split_by_section(text,section_pattern=r"\d+\.\d+"): """ 按章节号分割字符串 section_pattern: 章节号的正则模式,如 r'\d+\.\d+' 匹配 "20.1", "1.1" 等 """ # 在章节号前分割,保留章节号 pattern=f"({section_pattern})" parts=re.split(pattern,text) result=[] for i in range(1,len(parts),2):#这段代码的作用是将分割后的奇数索引和偶数索引部分重新组合 if i+1<len(parts): content=(parts[i] + parts[i+1]).strip() if content: result.append(content) return result datalines=data.splitlines() for line in datalines: if "第" in line:print(line) sections=split_by_section(line) for m in sections: print(m)

分割特点re.split()保留分隔符时,分隔符会出现在奇数索引位置(1,3,5...),而内容在偶数索引位置(2,4,6...)。所以写成

for i in range(1,len(parts),2):#这段代码的作用是将分割后的奇数索引和偶数索引部分重新组合 if i+1<len(parts): content=(parts[i] + parts[i+1]).strip()

strip()是 Python 字符串的内置方法,用于去除字符串首尾的空白字符

即可完成。

一日一画

代码如下:

import turtle turtle.tracer(False) colorlist=['purple','blue','green','red','orange'] edge=6 d=0 k=1 for j in range(1000): for i in range(edge): turtle.fd(k) d+=362/edge turtle.pencolor(colorlist[j%5]) turtle.seth(d) k+=1 turtle.down()

图形如下:

即可完成。

http://www.jsqmd.com/news/472675/

相关文章:

  • C#毕业设计——基于C#+asp.net+SVG的基于SVG的自动站雨量分析系统设计与实现(毕业论文+程序源码)——雨量分析系统
  • 第3篇 附录:Spring Boot + WebSocket + 消息队列STOMP协议 示例-- 只有 前台页面
  • 探索Mask R-CNN:深度学习中的图像分割神器
  • Hive中rlike,like区别与使用详解
  • MAPPO动作类型改进(二)——MAPPO+连续环境
  • 2026年南京名酒回收市场选择参考:茅台、老酒、虫草及礼品回收服务指南 - 海棠依旧大
  • 多模态跟踪怎么搞?清华西电TPAMI 2025新方法深度解析,从小白到大神,吃透这一篇就够了!
  • 【Mutilism用传输门搭建D触发器/与非门/或非门】2022-3-11
  • C#毕业设计——基于C#+asp.net+SQL Server的课程指导平台设计与实现(毕业论文+程序源码)——课程指导平台
  • 2026年3月南京名酒回收机构选择指南:茅台回收、老酒回收、洋酒回收、红酒回收、虫草回收机构 - 海棠依旧大
  • 笔试题-_-
  • Simpleperf 性能工具介绍app_profiler.py -i perf.data
  • C#毕业设计——基于C#+asp.net+SQL server的通用作业批改系统设计与实现(毕业论文+程序源码)——作业批改系统
  • 2026年江苏名酒回收机构推荐榜:名酒 / 老酒 / 虫草回收、上门服务、商家选择指南,盛鑫回收用专业鉴定守护靠谱交易 - 海棠依旧大
  • anaconda常用指令
  • “水莲花数”
  • 2026年成都/自贡/内江/泸州/宜宾/乐山/四川/云南云梯车、高空车、吊车、挖掘机、压路机、铲车租赁市场盘点:如何甄选可靠服务伙伴? - 2026年企业推荐榜
  • Ubuntu 22.04 搭建onlyoffice私服
  • 欧洲智慧零售及无人店铺展代理:好评度高选择策略解析
  • Logstash 项目教程:从零开始构建数据管道
  • ubantu环境初始化
  • 零基础Java第二期:数据类型与变量
  • 2026年3月江苏名酒回收公司选择指南:茅台回收、名酒老酒回收、洋酒红酒回收、虫草回收机构 - 海棠依旧大
  • 英国伯明翰电子烟展门票办理:靠谱合作公司选择的5大核心策略
  • 2026年3月杭州租车公司选择指南:商务、婚车、大巴、考斯特、豪车、旅游包车租车公司推荐 - 海棠依旧大
  • STM32开发入门(一):在 Keil 上新建 Project 工程
  • 数据的存储(原反补码/大小端存储/截断溢出/隐式类型转换/浮点数存储)
  • 老三网址读取
  • 前端反接保护:实用方案解析与探讨
  • 2026年杭州租车服务指南:商务出行、旅游包车、婚车车队及汽车租赁公司选择建议,卓强汽车用十年沉淀护航每一次安心旅程 - 海棠依旧大