import re
from docx import Document
def should_skip_line(line: str) -> bool:
"""Skip unwanted lines containing names, timestamps, and other irrelevant data."""
skip_patterns = [
r'\b(?:mr|ms|dr|mrs)\b', # Titles
r'\b\d{1,2}\s*(?:am|pm)\b', # Time patterns
r'^Page\s*\d+$', # Page numbers
r'^\s*$', # Empty spaces
]
return any(re.search(pattern, line, re.IGNORECASE) for pattern in skip_patterns)
def extract_text_from_docx(filepath):
doc = Document(filepath)
content_parts = []
for para in doc.paragraphs:
text = para.text.strip()
if text and not should_skip_line(text):
content_parts.append(text)
return '\n'.join(content_parts)
示例用法
doc_text = extract_text_from_docx("example.docx")
print(doc_text)
我面对的问题: 提取后一些议程项目缺失或错位。 有时仍然会出现不需要的元素,例如名称和时间戳。 项目编号不是顺序的(由于文档格式不规则而被混合在一起)。
确保仅适当提取相关议程 忽略页码或随机文本时保留适当的编号 改进文本对齐,使其正确出现在结构化表格式中Suggestion:如果没有实际示例,我们只能推测。 您仍然得到日期的事实意味着您的正则是不正确的。 如果您因图案而跳过内容,则可以迎合调整。也许用“空格”代替跳过的图案。 如果您不这样做,那么DOC流就到处都是,您需要保留DOC结构。