docx-parse-resilient
Qué hace
Esta skill es un enfoque de dos pasos para leer archivos .docx, en el que un respaldo en Python toma el relevo cuando falla el método de shell. Está pensada para quienes trabajan en contenedores o entornos mínimos donde las herramientas disponibles varían.
Cuándo usarla
- ✓Cuando el comando unzip devuelve un error o ninguna salida con un archivo Word.
- ✓Cuando trabajo en un contenedor, un trabajo de CI o un entorno mínimo con pocas herramientas.
- ✓Cuando necesito una extracción de texto de Word fiable que cambie sola a una alternativa.
Link de la skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/docx-shell-parse-enhanced/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Extrae el texto de este archivo Word. Si el comando unzip no da nada, cambia a Python y vuelve a intentarlo.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
La IA ejecuta primero la extracción por shell, comprueba si se obtuvo algún texto y, si el resultado está vacío, lee el XML del archivo Word con el módulo zipfile de Python.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de 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-docxbutzipfilemodule is available (standard library) - Working in constrained or inconsistent environments (containers, minimal images, CI/CD)
- Shell
unzipcommand 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:
- Primary (Shell):
unzip -p+sedfor fast extraction - Fallback (Python):
zipfilemodule 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
Preguntas frecuentes
¿Se comprueba primero el archivo?
Sí. La guía empieza confirmando que el archivo Word existe antes de extraer su texto.
¿Qué comprueba la alternativa?
Comprueba si la extracción por shell devolvió algún contenido.
¿Por qué usar zipfile?
Forma parte de la biblioteca estándar de Python, así que no necesita instalación adicional.
Detalles
Descripción original del autor
Extract text from DOCX files with shell-primary approach and Python zipfile fallback for maximum reliability
repo: HKUDS/AgentPilot
Popularidad
- Estrellas en GitHub
- 7,8 mil
- Posición en el ranking
- #12869
- Licencia
- MIT
- Actualizada
- 1/11/2026
Comentarios
- …
Más skills de este repositorio
agentpilot
7,8 milAyuda a tu agente a mejorar un proyecto paso a paso, preparando una tarea y ejecutando el bucle de AgentPilot que propone, prueba y puntúa cambios.
openspace
7,8 milAyuda a tu agente a configurar OpenSpace, una herramienta que guarda y recupera skills de agentes, y a conectarla a tu app de IA mediante MCP.
rsi-arena
7,8 milAyuda a tu agente a configurar y ejecutar pruebas de referencia de IA conocidas, como AIME y Terminal-Bench, para comparar distintos métodos de mejora.
experiment-guide
7,8 milAyuda a tu agente a planificar experimentos pequeños, leer sus resultados y anotar conclusiones mientras investiga cómo mejorar un programa.
Skills parecidas
feishu-doc
394 milAyuda a tu agente a leer, crear y editar documentos en la nube de Feishu, incluidos texto, imágenes y tablas, usando la herramienta de documentos.
feishu-drive
394 milPermite que tu agente explore, organice y comente archivos de una carpeta de la nube de Feishu que se haya compartido con el bot.
feishu-perm
394 milAyuda a tu agente a revisar y cambiar quién puede acceder a un archivo de Feishu, eligiendo el permiso más pequeño que cumpla tu petición.