1概览
本 notebook 演示如何使用 Semantica 的解析模块解析各种文档格式。你将学习从 PDF、DOCX、CSV、JSON、XML 和 HTML 文件中抽取文本、元数据和结构化数据。
文档:API 参考
学习目标
- 使用
DocumentParser进行通用文档解析 - 使用特定格式的解析器:
PDFParser、DOCXParser、CSVParser、JSONParser、XMLParser、HTMLParser - 从文档中抽取文本内容和元数据
- 解析结构化数据格式
2安装
从 PyPI 安装 Semantica:
pip install semantica
# 或安装所有可选依赖:
pip install semantica[all]
3步骤 1:文档解析器
使用通用 DocumentParser 解析各种文档格式。
# 安装 semantica 包
!pip install semantica
# 使用通用 DocumentParser 抽取文本内容与元数据
from semantica.parse import DocumentParser
import tempfile
import os
document_parser = DocumentParser()
# 创建临时目录并写入示例文本文件
temp_dir = tempfile.mkdtemp()
sample_txt = os.path.join(temp_dir, "sample.txt")
with open(sample_txt, 'w') as f:
f.write("Apple Inc. is a technology company. Tim Cook is the CEO.")
# 抽取文本与元数据
text = document_parser.extract_text(sample_txt)
metadata = document_parser.extract_metadata(sample_txt)
text[:50], metadata
4步骤 2:CSV 解析器
解析 CSV 文件以抽取结构化数据。
# 解析 CSV 文件以抽取结构化表格数据
from semantica.parse import CSVParser
csv_parser = CSVParser()
csv_file = os.path.join(temp_dir, "data.csv")
# 写入带表头的示例 CSV 数据
with open(csv_file, 'w') as f:
f.write("name,company,role\n")
f.write("Tim Cook,Apple Inc.,CEO\n")
f.write("Satya Nadella,Microsoft Corporation,CEO\n")
csv_data = csv_parser.parse(csv_file)
# 输出行数、列名与前两行数据
print(f"Parsed CSV with {len(csv_data.rows)} rows")
print(f"Columns: {csv_data.headers}")
for row in csv_data.rows[:2]:
print(f" {row}")
5步骤 3:JSON 解析器
解析 JSON 文件以抽取结构化数据。
# 解析 JSON 文件以抽取结构化数据
from semantica.parse import JSONParser
import json
json_parser = JSONParser()
json_file = os.path.join(temp_dir, "data.json")
# 构造示例 JSON 数据并写入文件
data = {
"companies": [
{"name": "Apple Inc.", "ceo": "Tim Cook"},
{"name": "Microsoft Corporation", "ceo": "Satya Nadella"}
]
}
with open(json_file, 'w') as f:
json.dump(data, f)
json_data = json_parser.parse(json_file)
print(f"Parsed JSON: {json_data.data}")
print(f"Companies: {len(json_data.data.get('companies', []))}")
6步骤 4:XML 解析器
解析 XML 文件以抽取结构化数据。
# 解析 XML 文件以抽取结构化数据
from semantica.parse import XMLParser
xml_parser = XMLParser()
xml_file = os.path.join(temp_dir, "data.xml")
# 定义示例 XML 内容并写入文件
xml_content = """<?xml version="1.0"?>
<companies>
<company name="Apple Inc." ceo="Tim Cook"/>
<company name="Microsoft Corporation" ceo="Satya Nadella"/>
</companies>"""
with open(xml_file, 'w') as f:
f.write(xml_content)
xml_data = xml_parser.parse(xml_file)
print(f"Parsed XML with {len(xml_data.root.children)} elements")
print(f"Root element: {xml_data.root.tag if xml_data.root else 'None'}")
7步骤 5:HTML 解析器
解析 HTML 文件以抽取内容和结构。
# 解析 HTML 文件以抽取页面标题与正文内容
from semantica.parse import HTMLParser
html_parser = HTMLParser()
html_file = os.path.join(temp_dir, "page.html")
# 定义示例 HTML 页面并写入文件
html_content = """<html>
<head><title>Sample Page</title></head>
<body>
<h1>Technology Companies</h1>
<p>Apple Inc. is a technology company.</p>
</body>
</html>"""
with open(html_file, 'w') as f:
f.write(html_content)
html_data = html_parser.parse(html_file)
print(f"Parsed HTML")
print(f"Title: {html_data.metadata.get('title', 'N/A')}")
print(f"Text content: {html_data.text[:50]}...")
8步骤 6:结构化数据解析器
使用 StructuredDataParser 处理多种格式。
# 使用 StructuredDataParser 统一解析多种结构化格式
from semantica.parse import StructuredDataParser
structured_parser = StructuredDataParser()
# 复用前面生成的 JSON 与 CSV 文件,按格式参数解析
parsed_json = structured_parser.parse_data(json_file, data_format="json")
parsed_csv = structured_parser.parse_data(csv_file, data_format="csv")
print(f"Structured parser parsed JSON: {len(parsed_json.get('data', {}).get('companies', []))} companies")
print(f"Structured parser parsed CSV: {len(parsed_csv.get('rows', []))} rows")
9小结
你已经学会了如何解析各种文档格式:
- DocumentParser:通用文档解析
- CSVParser:CSV 文件解析
- JSONParser:JSON 文件解析
- XMLParser:XML 文件解析
- HTMLParser:HTML 文件解析
- StructuredDataParser:多格式结构化数据解析
下一步:在 Data_Normalization notebook 中学习如何规范化和清洗数据。