ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Python | DOCX批量转TXT

Python | DOCX批量转TXT jupyter notebook(python 3.12.7) win32com.client说明首先用了python-docx的方式但由于docx包含了表格内容导致输出的txt文件存在重复行或内容缺失代码调整会更复杂因此换成了win32com.client方式。1.指定docx文档的文件夹运行代码转txtimport os import win32com.client from tqdm import tqdm # 进度条库需要安装pip install tqdm def batch_convert_docx_to_txt(input_folder, output_folder): # 初始化COM对象 wps win32com.client.DispatchEx(KWPS.Application) # 使用独立进程 wps.Visible False # 不可见模式 # 创建输出目录 os.makedirs(output_folder, exist_okTrue) # 获取文件列表并过滤系统文件 docx_files [ f for f in os.listdir(input_folder) if f.lower().endswith(.docx) and not f.startswith(~$) ] # 转换统计 success 0 failed_files [] # 带进度条处理 with tqdm(totallen(docx_files), unitfile, desc转换进度) as pbar: for filename in docx_files: input_path os.path.join(input_folder, filename) output_filename os.path.splitext(filename)[0] .txt output_path os.path.join(output_folder, output_filename) try: # 打开文档禁止宏运行 doc wps.Documents.Open( FileNameinput_path, ConfirmConversionsFalse, ReadOnlyTrue, AddToRecentFilesFalse, NoEncodingDialogTrue ) # 保存配置UTF-8编码 doc.SaveAs( FileNameoutput_path, FileFormat7, # txt格式 Encoding65001, # UTF-8编码 LineEnding1, # Windows换行符 AddToRecentFilesFalse ) success 1 except Exception as e: failed_files.append((filename, str(e))) finally: # 确保释放文档资源 if doc in locals() and doc: doc.Close(SaveChangesFalse) del doc pbar.update(1) # 清理资源 wps.Quit() del wps # 输出报告 print(f\n转换完成成功{success}/{len(docx_files)}) if failed_files: print(失败文件清单) for f, err in failed_files: print(f• {f}: {err}) # 使用示例 if __name__ __main__: input_dir rD:\DOCX_TO_TXT\src # 原始文档路径 output_dir rD:\DOCX_TO_TXT\output # 输出路径 batch_convert_docx_to_txt(input_dir, output_dir)注意把代码中的文件夹替换成自己需要的运行结果docx批量转换成txt后可以用于做语义分析、词云图等。2.再txt多文档合并成一个文档运行代码import os import glob from tqdm import tqdm # 进度条库需安装pip install tqdm def merge_txt_files( input_dir: str, output_file: str merged.txt, sort_by: str name, encoding: str utf-8, separator: str \n\n, file_pattern: str *.txt, recursive: bool False ): 合并多个TXT文件 参数 input_dir: 输入目录路径 output_file: 输出文件路径默认当前目录/merged.txt sort_by: 排序方式 [name, mtime, ctime, size]默认按文件名 encoding: 文件编码默认utf-8 separator: 文件内容分隔符默认两个换行 file_pattern: 文件匹配模式默认*.txt recursive: 是否递归搜索子目录默认False # 获取文件列表 pattern os.path.join(input_dir, **, file_pattern) if recursive else os.path.join(input_dir, file_pattern) file_list glob.glob(pattern, recursiverecursive) if not file_list: raise FileNotFoundError(f在 {input_dir} 中未找到匹配 {file_pattern} 的文件) # 排序策略 sort_functions { name: lambda x: x, mtime: lambda x: os.path.getmtime(x), ctime: lambda x: os.path.getctime(x), size: lambda x: os.path.getsize(x) } if sort_by not in sort_functions: raise ValueError(f无效的排序方式可选值{list(sort_functions.keys())}) file_list.sort(keysort_functions[sort_by]) # 合并处理 merged_size 0 # ✅ 正确缩进 error_files [] # ✅ 正确缩进 with open(output_file, w, encodingencoding) as outfile: for file_path in tqdm(file_list, desc合并进度, unitfile): try: with open(file_path, r, encodingencoding) as infile: content infile.read() outfile.write(f【文件来源】{os.path.basename(file_path)}\n) outfile.write(content) outfile.write(separator) merged_size len(content) except UnicodeDecodeError: # 尝试自动检测编码 try: with open(file_path, r, encodinggb18030) as infile: content infile.read() outfile.write(f【文件来源】{os.path.basename(file_path)} (GBK编码)\n) outfile.write(content) outfile.write(separator) merged_size len(content) except Exception as e: error_files.append((file_path, str(e))) except Exception as e: error_files.append((file_path, str(e))) # 生成报告 print(f\n合并完成) print(f输入文件数{len(file_list)}) print(f成功合并{len(file_list) - len(error_files)}) print(f合并后大小{merged_size / 1024 / 1024:.2f} MB) if error_files: print(\n错误文件列表) for file, error in error_files: print(f• {os.path.basename(file)}: {error}) if __name__ __main__: # 使用示例 merge_txt_files( input_dirrD:\txt多文档, output_filerD:\combined_docs.txt, sort_bymtime, # 按修改时间排序 separator\n -*50 \n, # 自定义分隔符 recursiveTrue # 包含子目录 )注意把代码中的文件夹替换成自己需要的input_dir是指定的输入txt文档的文件夹output_file是指定的输出合并文档的路径名称。
返回列表