import textract import re import os def read_word_text(docx_path): # 使用 textract 提取 Word 文档中的文本 text = textract.process(docx_path).decode('utf-8') return text def clean_text(text): # 1. 移除段内不必要的换行 # 将段落内的换行符替换为空格 text = re.sub(r'(\S)\n(\S)', r'\1 \2', text) # 2. 保留段落之间的换行 # 合并连续的空行 cleaned_text = re.sub(r'\n\s*\n+', '\n\n', text) # 3. 去除每行开头和结尾的空白字符 cleaned_text = re.sub(r'^\s+|\s+$', '', cleaned_text, flags=re.MULTILINE) return cleaned_text def remove_unwanted_content(text): # 1. 去除目录 text = re.sub(r'^目录.*?\n', '', text, flags=re.DOTALL | re.MULTILINE) # 2. 去除页眉和页脚 # 假设页眉和页脚通常是每页的第一行和最后一行 lines = text.split('\n') new_lines = [] for i in range(0, len(lines), 2): # 每两行处理一次 if i + 1 < len(lines): # 去除页眉和页脚 new_lines.append(lines[i + 1]) text = '\n'.join(new_lines) # 3. 去除注释 text = re.sub(r'$.*?$', '', text) # 去除括号内的注释 text = re.sub(r'\*.*?\*', '', text) # 去除星号内的注释 # 4. 去除空行和多余的空白 text = re.sub(r'\n\s*\n+', '\n\n', text) return text def format_special_terms(text): # 识别图、表、Figure、Table等关键词,并在它们之前插入换行符 text = re.sub(r'(? ', text) return text def save_text_as_utf8(text, output_path): # 将文本以 UTF-8 格式保存到文件 with open(output_path, 'w', encoding='utf-8') as file: file.write(text) def main(docx_path): # 提取 Word 文件名 docx_filename = os.path.basename(docx_path) docx_name, _ = os.path.splitext(docx_filename) # 创建新文件夹 output_dir = 'word_output' if not os.path.exists(output_dir): os.makedirs(output_dir) # 构建输出文件路径 output_path = os.path.join(output_dir, f"{docx_name}.txt") # 提取文本 word_text = read_word_text(docx_path) # 清理文本 cleaned_text = clean_text(word_text) # 去除不需要的信息 cleaned_text = remove_unwanted_content(cleaned_text) # 格式化特殊术语 final_text = format_special_terms(cleaned_text) # 保存清理后的文本 save_text_as_utf8(final_text, output_path) print(f"Text extracted, cleaned, and saved to {output_path} in UTF-8 format.") if __name__ == "__main__": docx_path = r'C:\Users\Machenike\Desktop\火工大\hgd240914\1图像目标智能识别软件设计方案.docx' # 请确保这里的路径正确指向您的 Word 文件 main(docx_path)