{"data":{"slug":"github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-word-analysis-5aad4bf1619d","title":"Extract Text and Tables from Word Documents","summary":"Extract full text, tables, and formatting details from .docx and .doc files. Supports multi-file aggregation and color\/format analysis.","url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-word-analysis-5aad4bf1619d","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-word-analysis-5aad4bf1619d","markdown_url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-word-analysis-5aad4bf1619d.md","download_url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-word-analysis-5aad4bf1619d\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"The tool requires Python and the python-docx library. For .doc files, conversion to .docx using LibreOffice is necessary before processing.","instructions":"---\nname: word-analysis\ndescription: \"Word (.docx\/.doc) \u6587\u6863\u5168\u91cf\u89e3\u6790\u3002\u8986\u76d6\uff1a\u6b63\u6587\/\u6bb5\u843d\u6587\u672c\u63d0\u53d6\u3001\u8868\u683c\u6570\u636e\u63d0\u53d6\u3001\u9ad8\u4eae\/\u989c\u8272\u683c\u5f0f\u8bfb\u53d6\u3001\u591a\u6587\u4ef6\u6c47\u603b\u5bf9\u6bd4\u3001\u5d4c\u5165\u56fe\u7247\u8f6c caption\u3002\"\n---\n\n# Word Analysis \u2014 .docx \/ .doc\n\n## Environment\n\n```python\nfrom docx import Document\nimport os\n\n# python-docx is available; for .doc (old format) convert via libreoffice first\ndef load_doc(path):\n    \"\"\"Load .docx directly; convert .doc to .docx first if needed.\"\"\"\n    if path.lower().endswith('.doc'):\n        import subprocess\n        out_dir = os.path.dirname(path)\n        subprocess.run(\n            ['libreoffice', '--headless', '--convert-to', 'docx', '--outdir', out_dir, path],\n            check=True, capture_output=True\n        )\n        path = path.rsplit('.', 1)[0] + '.docx'\n    return Document(path)\n```\n\n---\n\n## Core Method 1: Full Text Extraction\n\n```python\ndef extract_full_text(doc_path):\n    \"\"\"Extract all text: paragraphs + table cells, in document order.\"\"\"\n    doc = load_doc(doc_path)\n    lines = []\n\n    # Iterate paragraphs and tables in body order\n    from docx.oxml.ns import qn\n    for block in doc.element.body:\n        tag = block.tag.split('}')[-1]\n        if tag == 'p':\n            # Paragraph\n            from docx.text.paragraph import Paragraph\n            para = Paragraph(block, doc)\n            text = para.text.strip()\n            if text:\n                lines.append(text)\n        elif tag == 'tbl':\n            # Table\n            from docx.table import Table\n            tbl = Table(block, doc)\n            for row in tbl.rows:\n                row_text = '\\t'.join(cell.text.strip() for cell in row.cells)\n                if row_text.strip():\n                    lines.append(row_text)\n\n    return '\\n'.join(lines)\n\n# Usage\ntext = extract_full_text(\"\/mnt\/data\/doc.docx\")\nprint(text[:2000])  # preview first 2000 chars\n```\n\n---\n\n## Core Method 2: Table Extraction (Structured)\n\n```python\nimport pandas as pd\n\ndef extract_all_tables(doc_path):\n    \"\"\"Extract all tables from a Word document as list of DataFrames.\"\"\"\n    doc = load_doc(doc_path)\n    tables = []\n\n    for i, tbl in enumerate(doc.tables):\n        rows = []\n        for row in tbl.rows:\n            rows.append([cell.text.strip() for cell in row.cells])\n        if not rows:\n            continue\n        # Use first row as header if it looks like a header\n        df = pd.DataFrame(rows[1:], columns=rows[0]) if rows else pd.DataFrame()\n        tables.append((i, df))\n        print(f\"Table {i}: {df.shape[0]} rows \u00d7 {df.shape[1]} cols\")\n        print(df.head(3))\n\n    return tables\n\n# Usage\ntables = extract_all_tables(\"\/mnt\/data\/doc.docx\")\n```\n\n---\n\n## Core Method 3: Format-Aware Extraction (Color \/ Highlight)\n\nSome questions require reading cell background color or text highlight color\n(e.g., \"\u6807\u9ec4\u7684\u884c\", \"\u7ea2\u8272\u6587\u5b57\"). Use XML-level access:\n\n```python\nfrom docx import Document\nfrom docx.oxml.ns import qn\nfrom lxml import etree\n\ndef get_paragraph_highlight(para):\n    \"\"\"Return highlight color name of first run, or None.\"\"\"\n    for run in para.runs:\n        rPr = run._r.find(qn('w:rPr'))\n        if rPr is not None:\n            hl = rPr.find(qn('w:highlight'))\n            if hl is not None:\n                return hl.get(qn('w:val'))  # e.g. 'yellow', 'cyan', 'red'\n    return None\n\ndef get_table_cell_shading(cell):\n    \"\"\"Return background color hex of a table cell, or None.\"\"\"\n    tcPr = cell._tc.find(qn('w:tcPr'))\n    if tcPr is not None:\n        shd = tcPr.find(qn('w:shd'))\n        if shd is not None:\n            return shd.get(qn('w:fill'))  # hex color, e.g. 'FFFF00'\n    return None\n\n# Example: find all highlighted paragraphs\ndef find_highlighted_rows(doc_path, color='yellow'):\n    doc = load_doc(doc_path)\n    highlighted = []\n    for i, para in enumerate(doc.paragraphs):\n        hl = get_paragraph_highlight(para)\n        if hl == color or (color == 'yellow' and hl in ('yellow', 'FFFF00')):\n            highlighted.append((i, para.text))\n    return highlighted\n\n# For table cells with yellow background:\ndef find_highlighted_table_cells(doc_path, fill_colors=('FFFF00', 'FFD700')):\n    doc = load_doc(doc_path)\n    results = []\n    for t_idx, tbl in enumerate(doc.tables):\n        for r_idx, row in enumerate(tbl.rows):\n            for c_idx, cell in enumerate(row.cells):\n                color = get_table_cell_shading(cell)\n                if color and color.upper() in fill_colors:\n                    results.append({\n                        'table': t_idx, 'row': r_idx, 'col': c_idx,\n                        'color': color, 'text': cell.text.strip()\n                    })\n    return results\n```\n\n---\n\n## Core Method 4: Multi-File Aggregation\n\nWhen the user asks about \"these files\" or the input is a directory:\n\n```python\ndef process_all_docs(file_list, extractor_fn):\n    \"\"\"Apply extractor to all files and aggregate results.\"\"\"\n    all_results = []\n    for path in file_list:\n        print(f\"\\n=== Processing: {os.path.basename(path)} ===\")\n        try:\n            result = extractor_fn(path)\n            all_results.append({'file': os.path.basename(path), 'data': result})\n        except Exception as e:\n            print(f\"  ERROR: {e}\")\n    return all_results\n\n# Example: extract text from all .docx in a directory\ndoc_files = [f for f in all_files if f.lower().endswith(('.docx', '.doc'))]\nresults = process_all_docs(doc_files, extract_full_text)\n```\n\n---\n\n## Core Method 5: Embedded Images \u2192 Caption\n\nWhen a Word doc contains embedded images (charts, screenshots):\n\n```python\nimport zipfile, io, subprocess, json\n\nCAPTION = \"\/path\/to\/skills\/sn-da-image-caption\/scripts\/caption.py\"\n\ndef extract_and_caption_images(doc_path, prompt=None):\n    \"\"\"Extract all images from .docx and caption each one.\"\"\"\n    # .docx is a ZIP archive; images are in word\/media\/\n    results = []\n    with zipfile.ZipFile(doc_path, 'r') as z:\n        media_files = [n for n in z.namelist() if n.startswith('word\/media\/')]\n        for media in media_files:\n            ext = os.path.splitext(media)[-1].lower()\n            if ext not in ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.wmf', '.emf'):\n                continue\n            # Save to temp\n            tmp_path = f\"\/tmp\/{os.path.basename(media)}\"\n            with z.open(media) as src, open(tmp_path, 'wb') as dst:\n                dst.write(src.read())\n            # Caption\n            cmd = [\"python3\", CAPTION, tmp_path, \"--json\"]\n            if prompt:\n                cmd += [\"--prompt\", prompt]\n            r = subprocess.run(cmd, capture_output=True, text=True, timeout=60)\n            if r.returncode == 0:\n                desc = json.loads(r.stdout).get(\"description\", \"\")\n                results.append({'image': media, 'caption': desc})\n                print(f\"  {media}: {desc[:100]}...\")\n            else:\n                print(f\"  {media}: caption failed \u2014 {r.stderr[:80]}\")\n    return results\n```\n\n---\n\n## Common Patterns\n\n### Font\/size check (\u5b57\u53f7\u68c0\u67e5)\n```python\nfrom docx.shared import Pt\n\ndef check_font_sizes(doc_path):\n    doc = load_doc(doc_path)\n    issues = []\n    for i, para in enumerate(doc.paragraphs):\n        for run in para.runs:\n            size = run.font.size\n            size_pt = size.pt if size else None\n            # Also check style-level font\n            if size_pt is None:\n                style_size = run.style.font.size if run.style else None\n                size_pt = style_size.pt if style_size else None\n            issues.append({'para': i, 'text': run.text[:30], 'size_pt': size_pt})\n    return issues\n```\n\n### Spell\/grammar check (\u9519\u522b\u5b57)\n- Use full-text extraction, then search with string matching or pass to LLM for proofreading\n- Do NOT try to install hunspell or other spell-check tools\n\n### Keyword search (\u5168\u6587\u5b9a\u4f4d)\n```python\ndef find_keyword(doc_path, keyword):\n    text = extract_full_text(doc_path)\n    idx = text.find(keyword)\n    if idx >= 0:\n        context = text[max(0, idx-100):idx+200]\n        print(f\"Found '{keyword}' at pos {idx}:\\n{context}\")\n    else:\n        print(f\"'{keyword}' not found. Try broader search.\")\n        # Try case-insensitive or partial match\n        for kw in keyword.split():\n            if kw in text:\n                print(f\"  Partial match for '{kw}'\")\n```\n\n---\n\n## Pitfalls\n\n| Pitfall | Fix |\n|---------|-----|\n| Only read `doc.paragraphs`, miss tables | Use the body-order iterator in Method 1 |\n| Single file when input is multi-file | Check `os.path.isdir()`, iterate all |\n| Highlighted cells not detected | Use XML-level `w:shd` \/ `w:highlight` (Method 3) |\n| `.doc` format fails to open | Convert to `.docx` via libreoffice (Method 0) |\n| Embedded charts look empty | Extract images from ZIP, caption each (Method 5) |\n| Font size is None | Check both run-level and style-level (Method for font check) |\n","use_cases":["Extract all text from a Word document for content analysis","Extract tables for data analysis or reporting","Identify highlighted text or colored cells for formatting analysis","Aggregate text from multiple Word files for comparison"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/OpenSenseNova\/SenseNova-Skills\/blob\/07e7ff8c4bdfd7b79e7402fe94af59d2a5a9749b\/skills\/sn-da-non-spreadsheet-analysis\/capability\/word-analysis\/SKILL.md","source_commit":"07e7ff8c4bdfd7b79e7402fe94af59d2a5a9749b","license":null,"version":null,"listing_approved_at":"2026-11-16","created_at":"2026-11-15T10:23:34.000000Z","updated_at":"2026-11-16T05:16:30.000000Z","seo_title":"Extract Text and Tables from Word Documents","seo_description":"Extract full text, tables, and formatting details from .docx and .doc files. Supports multi-file aggregation and color\/format analysis.","seo_keywords":["extract text from Word document","extract tables from Word file","highlighted text detection","Word document analysis","multi-file text extraction"]}}