中文擷取範例
LangExtract 完美支援中文、日文、韓文等非英語語言。
關鍵點
- Tokenization: LangExtract 自動處理多位元組字元。
- Prompt: 為獲得最佳效果,請使用與來源文本相同語言的 prompt。
程式碼範例
python
import langextract as lx
# 1. 中文輸入文本
input_text = """
台北市是中華民國的首都,常住人口約 250 萬人。
市長是蔣萬安。
"""
# 2. 中文 Prompt
prompt_description = """
請擷取以下資訊:
- 城市名 (City)
- 人口 (Population)
- 市長 (Mayor)
請從文本中精確擷取,不要改寫。
"""
# 3. 定義範例資料
examples = [
lx.data.ExampleData(
text="高雄市常住人口約 270 萬人,市長是陳其邁。",
extractions=[
lx.data.Extraction(extraction_class="city", extraction_text="高雄市"),
lx.data.Extraction(extraction_class="population", extraction_text="約 270 萬人"),
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: 約 250 萬人
• mayor: 蔣萬安