본문으로 건너뛰기
Skillpedia
PDF, Word, 슬라이드7.8k · #12869

docx-parse-resilient

하는 일

이 스킬은 .docx 파일을 읽는 두 단계 방법으로, 첫 번째 방법이 실패하면 Python 예비 방법을 사용합니다. 사용할 수 있는 도구가 제각각인 컨테이너나 최소 환경에서 작업하는 사람에게 맞습니다.

사용하는 경우

  • ✓Word 파일에서 unzip 명령이 오류를 내거나 결과를 내지 않을 때.
  • ✓컨테이너, CI 작업 또는 도구가 적은 최소 환경에서 작업할 때.
  • ✓자동으로 예비 방법을 쓰는 안정적인 Word 텍스트 추출이 필요한 경우.

스킬 링크

https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/docx-shell-parse-enhanced/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/docx-shell-parse-enhanced/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“이 Word 파일에서 텍스트를 추출해 주세요. unzip 명령이 아무것도 주지 않으면 Python으로 바꿔서 다시 시도해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

AI는 셸 추출을 먼저 실행하고 텍스트가 나왔는지 확인합니다. 결과가 비어 있으면 Python의 zipfile 모듈로 Word 파일의 XML을 읽습니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Resilient DOCX Text Extraction

Extract text from Microsoft Word (.docx) files using a robust two-tier approach: shell-based extraction as the primary method, with Python zipfile fallback when shell commands fail or return no output.

When to Use

  • Python environment may lack python-docx but zipfile module is available (standard library)
  • Working in constrained or inconsistent environments (containers, minimal images, CI/CD)
  • Shell unzip command returns errors or no output
  • Need reliable extraction with automatic fallback

Core Technique

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

  1. Primary (Shell): unzip -p + sed for fast extraction
  2. Fallback (Python): zipfile module for reliable extraction when shell fails

Step-by-Step Instructions

1. Verify the DOCX file exists

ls -la document.docx

2. Test shell extraction first (recommended)

Try the shell-based approach:

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

3. Check if shell extraction produced output

Verify the shell method returned content:

content=$(unzip -p document.docx word/document.xml 2>/dev/null | sed -e 's/<[^>]*>//g')
if [ -z "$content" ]; then
    echo "Shell extraction returned no output, trying Python fallback..."
fi

4. Use Python zipfile fallback if needed

When shell commands fail or return empty output, use Python's standard zipfile module:

python3 -c "
import zipfile
import sys
import re

try:
    with zipfile.ZipFile('document.docx', 'r') as z:
        content = z.read('word/document.xml').decode('utf-8')
        # Strip XML tags
        text = re.sub(r'<[^>]*>', '', content)
        # Clean whitespace
        lines = [line.strip() for line in text.split('\n') if line.strip()]
        print('\n'.join(lines))
except Exception as e:
    print(f'Error: {e}', file=sys.stderr)
    sys.exit(1)
"

5. Save extracted text to file

# Try shell first
unzip -p document.docx word/document.xml 2>/dev/null | \
  sed -e 's/<[^>]*>//g' > output.txt

# Verify output has content
if [ ! -s output.txt ]; then
    # Fallback to Python
    python3 -c "
import zipfile, re
with zipfile.ZipFile('document.docx', 'r') as z:
    content = z.read('word/document.xml').decode('utf-8')
    text = re.sub(r'<[^>]*>', '', content)
    lines = [line.strip() for line in text.split('\n') if line.strip()]
    print('\n'.join(lines))
" > output.txt
fi

Complete Shell Function with Fallback

Add this resilient function to your scripts:

parse_docx_resilient() {
    local file="$1"
    local output="$2"
    
    if [ ! -f "$file" ]; then
        echo "Error: File not found: $file" >&2
        return 1
    fi
    
    # Primary: Shell extraction
    local content
    content=$(unzip -p "$file" word/document.xml 2>/dev/null | \
        sed -e 's/<[^>]*>//g' | \
        sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | \
        sed -e '/^$/d')
    
    # Check if shell extraction succeeded
    if [ -n "$content" ]; then
        echo "$content" > "${output:-/dev/stdout}"
        return 0
    fi
    
    # Fallback: Python zipfile
    echo "Shell extraction failed, using Python fallback..." >&2
    python3 -c "
import zipfile, sys, re
try:
    with zipfile.ZipFile('$file', 'r') as z:
        content = z.read('word/document.xml').decode('utf-8')
        text = re.sub(r'<[^>]*>', '', content)
        lines = [line.strip() for line in text.split('\n') if line.strip()]
        print('\n'.join(lines))
except Exception as e:
    print(f'Python extraction failed: {e}', file=sys.stderr)
    sys.exit(1)
" > "${output:-/dev/stdout}" || return 1
}

# Usage examples:
# parse_docx_resilient document.docx          # Output to stdout
# parse_docx_resilient document.docx out.txt  # Output to file

Python Script Alternative

For complex workflows, save as a standalone script:

#!/usr/bin/env python3
"""DOCX text extractor with resilient fallback."""

import zipfile
import sys
import re
import subprocess

def extract_with_shell(filepath):
    """Try shell-based extraction first."""
    try:
        result = subprocess.run(
            ['unzip', '-p', filepath, 'word/document.xml'],
            capture_output=True, text=True, timeout=10
        )
        if result.returncode == 0 and result.stdout.strip():
            text = re.sub(r'<[^>]*>', '', result.stdout)
            lin
자주 묻는 질문

파일을 먼저 확인하나요?

네, 가이드는 텍스트를 추출하기 전에 Word 파일이 있는지 먼저 확인합니다.

예비 방법은 무엇을 확인하나요?

셸 추출이 어떤 내용이든 결과를 냈는지 확인합니다.

왜 zipfile을 쓰나요?

Python 표준 라이브러리의 일부이므로 따로 설치할 필요가 없습니다.

상세 정보

작성자의 원본 설명

Extract text from DOCX files with shell-primary approach and Python zipfile fallback for maximum reliability

repo: HKUDS/AgentPilot

인기도

GitHub 스타
7.8k
순위
#12869
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬