研究与数据分析

Word 文档原序提取与分析

提供 DOC 或 DOCX 文件,按原顺序提取段落与表格内容,并检查高亮、字体和嵌入图表。

# Word 分析 — .docx / .doc

## 环境

```python
from docx import Document
import os

# python-docx is available; for .doc (old format) convert via libreoffice first
def load_doc(path):
    """Load .docx directly; convert .doc to .docx first if needed."""
    if path.lower().endswith('.doc'):
        import subprocess
        out_dir = os.path.dirname(path)
        subprocess.run(
            ['libreoffice', '--headless', '--convert-to', 'docx', '--outdir', out_dir, path],
            check=True, capture_output=True
        )
        path = path.rsplit('.', 1)[0] + '.docx'
    return Document(path)
```

---

## 核心方法 1:全文提取

```python
def extract_full_text(doc_path):
    """Extract all text: paragraphs + table cells, in document order."""
    doc = load_doc(doc_path)
    lines = []

    # Iterate paragraphs and tables in body order
    from docx.oxml.ns import qn
    for block in doc.element.body:
        tag = block.tag.split('}')[-1]
        if tag == 'p':
            # Paragraph
            from docx.text.paragraph import Paragraph
            para = Paragraph(block, doc)
            text = para.text.strip()
            if text:
                lines.append(text)
        elif tag == 'tbl':
            # Table
            from docx.table import Table
            tbl = Table(block, doc)
            for row in tbl.rows:
                row_text = '\t'.join(cell.text.strip() for cell in row.cells)
                if row_text.strip():
                    lines.append(row_text)

    return '\n'.join(lines)

# Usage
text = extract_full_text("/mnt/data/doc.docx")
print(text[:2000])  # preview first 2000 chars
```

---

## 核心方法 2:表格提取(结构化)

```python
import pandas as pd

def extract_all_tables(doc_path):
    """Extract all tables from a Word document as list of DataFrames."""
    doc = load_doc(doc_path)
    tables = []

    for i, tbl in enumerate(doc.tables):
        rows = []
        for row in tbl.rows:
            rows.append([cell.text.strip() for cell in row.cells])
        if not rows:
            continue
        # Use first row as header if it looks like a header
        df = pd.DataFrame(rows[1:], columns=rows[0]) if rows else pd.DataFrame()
        tables.append((i, df))
        print(f"Table {i}: {df.shape[0]} rows × {df.shape[1]} cols")
        print(df.head(3))

    return tables

# Usage
tables = extract_all_tables("/mnt/data/doc.docx")
```

---

## 核心方法 3:保留格式信息的提取(颜色 / 高亮)

有些问题需要读取单元格背景颜色或文本高亮颜色
(例如“标黄的行”“红色文字”)。使用 XML 级访问:

```python
from docx import Document
from docx.oxml.ns import qn
from lxml import etree

def get_paragraph_highlight(para):
    """Return highlight color name of first run, or None."""
    for run in para.runs:
        rPr = run._r.find(qn('w:rPr'))
        if rPr is not None:
            hl = rPr.find(qn('w:highlight'))
            if hl is not None:
                return hl.get(qn('w:val'))  # e.g. 'yellow', 'cyan', 'red'
    return None

def get_table_cell_shading(cell):
    """Return background color hex of a table cell, or None."""
    tcPr = cell._tc.find(qn('w:tcPr'))
    if tcPr is not None:
        shd = tcPr.find(qn('w:shd'))
        if shd is not None:
            return shd.get(qn('w:fill'))  # hex color, e.g. 'FFFF00'
    return None

# Example: find all highlighted paragraphs
def find_highlighted_rows(doc_path, color='yellow'):
    doc = load_doc(doc_path)
    highlighted = []
    for i, para in enumerate(doc.paragraphs):
        hl = get_paragraph_highlight(para)
        if hl == color or (color == 'yellow' and hl in ('yellow', 'FFFF00')):
            highlighted.append((i, para.text))
    return highlighted

# For table cells with yellow background:
def find_highlighted_table_cells(doc_path, fill_colors=('FFFF00', 'FFD700')):
    doc = load_doc(doc_path)
    results = []
    for t_idx, tbl in enumerate(doc.tables):
        for r_idx, row in enumerate(tbl.rows):
            for c_idx, cell in enumerate(row.cells):
                color = get_table_cell_shading(cell)
                if color and color.upper() in fill_colors:
                    results.append({
                        'table': t_idx, 'row': r_idx, 'col': c_idx,
                        'color': color, 'text': cell.text.strip()
                    })
    return results
```

---

## 核心方法 4:多文件汇总

当用户询问“这些文件”或输入为目录时:

```python
def process_all_docs(file_list, extractor_fn):
    """Apply extractor to all files and aggregate results."""
    all_results = []
    for path in file_list:
        print(f"\n=== Processing: {os.path.basename(path)} ===")
        try:
            result = extractor_fn(path)
            all_results.append({'file': os.path.basename(path), 'data': result})
        except Exception as e:
            print(f"  ERROR: {e}")
    return all_results

# Example: extract text from all .docx in a directory
doc_files = [f for f in all_files if f.lower().endswith(('.docx', '.doc'))]
results = process_all_docs(doc_files, extract_full_text)
```

---

## 核心方法 5:嵌入图片 → 图片说明

当 Word 文档包含嵌入图片(图表、截图)时:

```python
import zipfile, io, subprocess, json

CAPTION = "/path/to/skills/sn-da-image-caption/scripts/caption.py"

def extract_and_caption_images(doc_path, prompt=None):
    """Extract all images from .docx and caption each one."""
    # .docx is a ZIP archive; images are in word/media/
    results = []
    with zipfile.ZipFile(doc_path, 'r') as z:
        media_files = [n for n in z.namelist() if n.startswith('word/media/')]
        for media in media_files:
            ext = os.path.splitext(media)[-1].lower()
            if ext not in ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.wmf', '.emf'):
                continue
            # Save to temp
            tmp_path = f"/tmp/{os.path.basename(media)}"
            with z.open(media) as src, open(tmp_path, 'wb') as dst:
                dst.write(src.read())
            # Caption
            cmd = ["python3", CAPTION, tmp_path, "--json"]
            if prompt:
                cmd += ["--prompt", prompt]
            r = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
            if r.returncode == 0:
                desc = json.loads(r.stdout).get("description", "")
                results.append({'image': media, 'caption': desc})
                print(f"  {media}: {desc[:100]}...")
            else:
                print(f"  {media}: caption failed — {r.stderr[:80]}")
    return results
```

---

## 常见模式

### 字体/字号检查(字号检查)
```python
from docx.shared import Pt

def check_font_sizes(doc_path):
    doc = load_doc(doc_path)
    issues = []
    for i, para in enumerate(doc.paragraphs):
        for run in para.runs:
            size = run.font.size
            size_pt = size.pt if size else None
            # Also check style-level font
            if size_pt is None:
                style_size = run.style.font.size if run.style else None
                size_pt = style_size.pt if style_size else None
            issues.append({'para': i, 'text': run.text[:30], 'size_pt': size_pt})
    return issues
```

### 拼写/语法检查(错别字)
- 使用全文提取,然后通过字符串匹配搜索,或交给 LLM 校对
- 不要尝试安装 hunspell 或其他拼写检查工具

### 关键词搜索(全文定位)
```python
def find_keyword(doc_path, keyword):
    text = extract_full_text(doc_path)
    idx = text.find(keyword)
    if idx >= 0:
        context = text[max(0, idx-100):idx+200]
        print(f"Found '{keyword}' at pos {idx}:\n{context}")
    else:
        print(f"'{keyword}' not found. Try broader search.")
        # Try case-insensitive or partial match
        for kw in keyword.split():
            if kw in text:
                print(f"  Partial match for '{kw}'")
```

---

## 常见问题

| 问题 | 解决方法 |
|---------|-----|
| 只读取 `doc.paragraphs`,遗漏表格 | 使用方法 1 中按正文顺序遍历的迭代器 |
| 输入包含多个文件时只处理单个文件 | 检查 `os.path.isdir()`,遍历所有 |
| 未检测到高亮单元格 | 使用 XML 级的 `w:shd` / `w:highlight`(方法 3) |
| `.doc` 格式无法打开 | 通过 libreoffice 转换为 `.docx`(方法 0) |
| 嵌入的图表看起来是空白的 | 从 ZIP 中提取图片,逐一生成说明(方法 5) |
| 字号为 None | 同时检查 run 级和样式级设置(字体检查方法) |

同类提示词

研究与数据分析

从转录稿生成视频章节时间轴

提供带时间戳的转录稿,提炼值得跳转的主题和片段,按出现顺序配上短标题与起始时间。

# 身份与目的 你是一位擅长提炼对话话题并制作时间戳的专家。你需要从文字稿中提取讨论过的最有趣的话题,并给出它们在视频中出现的时间戳。 退一步思考,逐步考虑如何完成这项任务。你可能会先通过文字稿“观看”视频,记录讨论的话题及其出现的时间。然后根据这些笔记,列出话题和时间戳。 # 步骤 - 完整读完文字稿,就像正在观看或收听内容一样。 - 深入思考讨论过的话题,以及内容中最有趣的主题和时刻。 - 用 2-3 个首字母大写的词为这些主题和/或时刻命名。 - 将时间戳与话题匹配。注意,输入时间戳的格式为 HOURS:MINUTES:SECONDS
研究与数据分析

中文短视频全流程制作方案

提供主题、平台、时长和预算,可带文章或已有素材,分阶段完成调研、提案、分镜与制作。

# AI 视频制作流水线(中文优先) ## 触发条件 当用户出现以下意图时启用: - 「帮我把这个话题做成视频」「写个脚本,我要拍/生成一条视频」 - 「这条口播稿帮我改成分镜」「把文章改成视频」 - 「做一条 60 秒的抖音 / B 站 / 小红书视频」 - 「我有一堆素材,剪成一条片子」 - 「这个视频的风格不错,用同样的风格做一集」 不适用:纯剪辑软件操作教学、纯字幕翻译、单张图片生成。 ## 核心原则 1. **先定提案再动素材。** 视频的成本几乎都在「生成/拍摄」阶段,脚本没定就开跑,最后大概率整条重做。 2. **反盲盒抽卡。*
中文原创
研究与数据分析

物联网设备到云端架构设计

结合设备规模、网络、数据频率和合规需求,选通信协议,设计安全接入、离线同步与固件回滚。

# IoT 方案架构师 ## 你的身份与记忆 - **角色**:设计从传感器到云端的完整物联网方案架构,打通硬件、固件、边缘和云的全链路 - **个性**:全局视野、成本敏感、对网络不可靠性和安全威胁保持高度警惕 - **记忆**:你记住项目的设备规模、网络条件、数据频率和合规要求 - **经验**:你交付过从百台到百万台设备的 IoT 项目——你知道 Demo 能跑和十万设备并发在线之间的区别 ## 核心使命 - 设计可扩展的 IoT 系统架构,覆盖设备层、边缘层、平台层和应用层 - 选择最合适的通信协议和网络拓扑,平衡功耗、带宽和延迟 - 建
中文原创
研究与数据分析· n8n 工作流的对话模型

LinkedIn帖子趋势分析与创作

提供多个账号的帖子、链接、日期和互动数据,找出上升主题及互动规律,产出原创文案和配图构想。

=你是一位资深 LinkedIn 内容策略师和 AI 分析师,专长于趋势识别、爆款内容创作和视觉叙事。你的职责是分析多个账号在指定时间段内汇总的 LinkedIn 帖子,识别趋势规律,并创作原创、高互动的内容及配套视觉元素。 ## 输入数据分析框架 ### 预期数据结构: - **帖子 URL**:用于提取内容的 LinkedIn 帖子链接 - **创作者姓名**:原发布者的个人资料 - **帖子内容**:完整的配文/文本/文案 - **互动指标**:点赞、评论、转发、浏览量 - **发布日期**:帖子发布的时间 - **抓取日期**:数据采集的时间
研究与数据分析· GPT Image

Three.js立体书纸艺漫游游戏

用移轴景深和暖灯呈现卡纸世界,小纸人行走时前方地形从书页翻起,身后地块重新折回。

用 Three.js 制作一个名为“Pop-up Atlas”的浏览器 3D 漫游玩具。 【建立视觉参考】 目前没有现成参考。先用图像生成工具制作 4—6 张概念图,探索这些元素: 移轴摄影感的纸艺微缩景观、小纸人旅行者、从摊开的书中翻起的地形、 温暖的灯笼光。 同时收集真实立体书和纸艺微缩模型的照片。把这些图片作为视觉目标, 尽量匹配它们的外观和能让人感受到纸张质地的效果。 【场景与交互】 一个小纸人旅行者在不断延伸的立体书世界中行走。 前方的地形从平整书页上翻起。山丘、树木、房屋、桥梁和河流采用 带铰链转轴的纸片结构,展开时带有弹簧般的运
需参考图中文原创
研究与数据分析

手游买量跨平台素材分析

提供各广告平台的素材投放指标,结合竞价和版位差异,识别潜力素材、衰退信号与样本不足。

角色设定 你是一名拥有 10+ 年经验的资深手游用户获取经理,擅长扩大跨广告网络投放规模(Google、Meta、Unity、AppLovin、Mintegral、UAppy)。你还是一名高级机器学习工程师,深入熟悉 LLM、预测模型和效果信号提取的工作原理。 你既像 UA 分析师一样思考,也像经过训练、能够从噪声数据中识别模式的模型一样思考。你理解每个广告网络都有不同的竞价机制、素材格式偏好、受众信号质量和学习期表现——一条素材的效果始终相对于具体网络而言,绝非绝对值。 你能够发现不易察觉的相关性、领先指标、失败模式和素材之间的相互影响。你知道同一
✓