Skip to content

中文提取示例

LangExtract 完美支持中文、日文、韩文等非英语语言。

关键点

  • Tokenization: LangExtract 自动处理多字节字符。
  • Prompt: 为获得最佳效果,请使用与源文本相同语言的 prompt。

代码示例

python
import langextract as lx

# 1. 中文输入文本
input_text = """
北京市是中国的首都,常住人口约 2185 万人。
市长是殷勇。
"""

# 2. 中文 Prompt
prompt_description = """
请提取以下信息:
- 城市名 (City)
- 人口 (Population)
- 市长 (Mayor)

请从文本中精确提取,不要改写。
"""

# 3. 定义示例数据
examples = [
    lx.data.ExampleData(
        text="上海市常住人口约 2489 万人,市长是龚正。",
        extractions=[
            lx.data.Extraction(extraction_class="city", extraction_text="上海市"),
            lx.data.Extraction(extraction_class="population", extraction_text="约 2489 万人"),
            lx.data.Extraction(extraction_class="mayor", extraction_text="龚正")
        ]
    )
]

# 4. 执行提取
result = lx.extract(
    text_or_documents=input_text,
    prompt_description=prompt_description,
    examples=examples,
    model_id="gemini-2.5-flash",
)

# 5. 显示结果
print("提取的实体:")
for entity in result.extractions:
    print(f"• {entity.extraction_class}: {entity.extraction_text}")

预期输出

提取的实体:
• city: 北京市
• population: 约 2185 万人
• mayor: 殷勇

非官方指南。与 Google 无关。