본문으로 건너뛰기
cccskills
무료GitHub에 공개

docx-dual-parse

Extract text from Word DOCX files and save it as plain text. The skill checks available tools, tries shell utilities, and falls back to Python’s standard library when needed.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

Extract text from DOCX files using shell or Python zipfile, with environment-aware fallback

연동 도구Word
설치 방법 보기

이럴 때 유용합니다

  • Extracting DOCX text for review
  • Reading Word files without python-docx
  • Extracting text in restricted containers
  • Saving document text to a file

포함된 파일(2)

  • SKILL.md7.0 KB
  • .skill_id46 B

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

DOCX Dual-Method Text Extraction

Extract text from Microsoft Word (.docx) files using either shell commands or Python's zipfile module, automatically selecting the most reliable method for your environment.

When to Use

  • Need reliable DOCX text extraction in varying environments (containers, sandboxes, minimal images)
  • Python environment may lack python-docx but has standard library access
  • Shell utilities (unzip, sed) may be unavailable or restricted
  • Want environment-aware fallback without manual intervention

Core Technique

DOCX files are ZIP archives containing XML files. This skill provides two extraction methods:

Method A (Shell): unzip -p + sed for tag stripping Method B (Python): zipfile module for archive access + string parsing

Environment Detection

Before extraction, detect which method will work:

# Quick shell method test
if unzip -v >/dev/null 2>&1; then
    echo "Shell method available"
else
    echo "Shell method unavailable, try Python"
fi
# Quick Python method test
python3 -c "import zipfile; print('Python method available')" 2>/dev/null

Method A: Shell-Based Extraction

Use when unzip and sed are available and the environment allows shell operations.

Step-by-Step Instructions

1. Verify the DOCX file exists

ls -la document.docx

2. Extract raw XML content

unzip -p document.docx word/document.xml

3. Strip XML tags from content

unzip -p document.docx word/document.xml | sed -e 's/<[^>]*>//g'

4. Clean up whitespace (optional)

unzip -p document.docx word/document.xml | \
  sed -e 's/<[^>]*>//g' | \
  sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | \
  sed -e '/^$/d'

5. Save extracted text to file

unzip -p document.docx word/document.xml | \
  sed -e 's/<[^>]*>//g' > output.txt

Reusable Shell Function

parse_docx_shell() {
    local file="$1"
    if [ ! -f "$file" ]; then
        echo "Error: File not found: $file" >&2
        return 1
    fi
    if ! command -v unzip >/dev/null 2>&1; then
        echo "Error: unzip not available" >&2
        return 1
    fi
    unzip -p "$file" word/document.xml 2>/dev/null | \
        sed -e 's/<[^>]*>//g' | \
        sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | \
        sed -e '/^$/d'
}

# Usage: parse_docx_shell document.docx

Method B: Python Zipfile Extraction

Use when shell method fails or Python environment is more reliable than shell.

Step-by-Step Instructions

1. Verify the DOCX file exists

ls -la document.docx

2. Run Python extraction via run_shell

run_shell 'python3 -c "
import zipfile
import re
with zipfile.ZipFile(\"document.docx\", \"r\") as z:
    content = z.read(\"word/document.xml\").decode(\"utf-8\")
    text = re.sub(r\"<[^>]*>\", \"\", content)
    lines = [l.strip() for l in text.splitlines() if l.strip()]
    for line in lines:
        print(line)
"'

3. Save to file by redirecting output

run_shell 'python3 -c "
import zipfile
import re
with zipfile.ZipFile(\"document.docx\", \"r\") as z:
    content = z.read(\"word/document.xml\").decode(\"utf-8\")
    text = re.sub(r\"<[^>]*>\", \"\", content)
    lines = [l.strip() for l in text.splitlines() if l.strip()]
    with open(\"output.txt\", \"w\") as f:
        for line in lines:
            f.write(line + \"\\n\")
"'

Reusable Python Function (via run_shell)

parse_docx_python() {
    local file="$1"
    local output="$2"
    if [ ! -f "$file" ]; then
        echo "Error: File not found: $file" >&2
        return 1
    fi
    run_shell "python3 -c \"
import zipfile
import re
import sys
try:
    with zipfile.ZipFile(\\'$file\\', \\'r\\') as z:
        content = z.read(\\'word/document.xml\\').decode(\\'utf-8\\')
        text = re.sub(r\\'<[^>]*>\\', \\'\\', content)
        lines = [l.strip() for l in text.splitlines() if l.strip()]
        for line in lines:
            print(line)
except Exception as e:
    print(f\\'Error: {e}\\', file=sys.stderr)
    sys.exit(1)
\""
}

# Usage: parse_docx_python document.docx
# Or to file: parse_docx_python document.docx > output.txt

Unified Dual-Method Function

Automatically tries shell first, falls back to Python if shell fails:

parse_docx() {
    local file="$1"
    if [ ! -f "$file" ]; then
        echo "Error: File not found: $file" >&2
        return 1
    fi
    
    # Try shell method first
    if command -v unzip >/dev/null 2>&1; then
        result=$(unzip -p "$file" word/document.xml 2>/dev/null | \
            sed -e 's/<[^>]*>//g' | \
            sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | \
            sed -e '/^$/d')
        if [ -n "$result" ]; then
            echo "$result"
            return 0
        fi
    fi
    
    # Fallback to Python method
    python3 -c "
import zipfile
import re
import sys
try:
    with zipfile.ZipFile('$file', 'r') as z:
        content = z.read('word/document.xml').decode('utf-8')
        text = re.sub(r'<[^>]*>', '', content)
        lines = [l.strip() for l in text.splitlines() if l.strip()]
        for line in lines:
            print(line)
except Exception as e:
    print(f'Error: {e}', file=sys.stderr)
    sys.exit(1)
"
}

# Usage: parse_docx document.docx

Alternative: Extract to Temporary Directory

For complex parsing needs or debugging:

Shell approach:

tmpdir=$(mktemp -d)
unzip document.docx -d "$tmpdir"
cat "$tmpdir/word/document.xml" | sed -e 's/<[^>]*>//g'
rm -rf "$tmpdir"

Python approach:

python3 -c "
import zipfile
import tempfile
import os
with zipfile.ZipFile('document.docx', 'r') as z:
    tmpdir = tempfile.mkdtemp()
    z.extractall(tmpdir)
    with open(os.path.join(tmpdir, 'word/document.xml')) as f:
        print(f.read())
"

Verification

Confirm extraction worked:

# Check output has content
parse_docx document.docx | head -20

# Verify file was created (if saving to file)
ls -la output.txt
wc -l output.txt

Method Selection Guide

EnvironmentRecommended Method
Standard Linux with unzipShell (faster, simpler)
Container without unzipPython zipfile
Sandboxed executionPython via execute_code_sandbox or run_shell
Minimal/busybox imagesShell if unzip available
Unknown/restrictedUse unified parse_docx function

Limitations

  • Does not preserve formatting, images, or table structure
  • May include some residual XML entity references ( , etc.)
  • Works best for simple text extraction needs
  • DOCX must be a valid Office Open XML format
  • Protected/encrypted DOCX files require additional handling

Error Handling Tips

  1. Always check file existence before parsing
  2. Test method availability in the target environment
  3. Capture stderr for debugging failed extractions
  4. Validate output is non-empty before proceeding
  5. Handle XML entity decoding if needed (sed can expand basic entities)

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Prepare audio stems, the separate parts of a track, for mixing by matching their durations with silence, loops, or crossfades. Verify each generated and processed file before moving to the next production step.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Match audio parts with different durations
  • Extend drums and melodic parts using suitable methods
  • Check audio specifications before mixing
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Produce audio in separate stems, meaning individual instrument tracks, and verify each output as you go. Align track lengths with silence, loops, or crossfades, then apply effects, mix a master, and package the files.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Align instrument tracks to a reference audio file
  • Choose how to extend tracks that are too short
  • Verify audio properties after generation and effects
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Build serverless endpoints that relay external API requests for a dashboard while keeping API keys on the server. Includes Vercel examples for input checks, caching, cross-origin access, and consistent JSON responses.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Connect a dashboard to external APIs without exposing API keys
  • Create endpoints for stock quotes and news
  • Standardize API responses and error handling
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Produce a master track and separate audio parts through a structured Python workflow. Apply filters and reverb, export WAV files with consistent settings, package them in a ZIP archive, and check that the deliverables meet the requested specifications.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Export a master track with separate audio parts
  • Apply filters and reverb to audio
  • Check duration and format across deliverables
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

Keep document creation moving when web searches and page retrieval repeatedly fail. The skill preserves the original task, uses the model’s existing knowledge, and clearly identifies information that could not be checked against external sources.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Continue drafting after repeated web retrieval failures
  • Preserve task requirements during network errors
  • Mark information that could not be externally verified
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

When Python execution repeatedly fails in execute_code_sandbox, use a file-based alternative: save the script, run it through the shell, and capture results or errors. The guidance covers paths, imports, timeouts, structured output, and optional cleanup.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Retry Python work through the shell after repeated sandbox failures
  • Run longer tasks with an adjusted timeout
  • Execute Python work that needs multiple files or system utilities
HKUDS/OpenSpace7.8천2026년 8월 13일 업데이트

HKUDS의 스킬 모두 보기

이 스킬의 문제 신고