政府公開資料集提供了大量經過整理、結構化的資訊,這些資料通常以XML或CSV格式釋出,具有極高的可靠性。這類資料集是建立RAG知識庫的絕佳起點,能為我的AI顧問紮下牢固的基礎。
假設我找到一個Trip.xml的旅遊資料集,使用Python內建的 xml.etree.ElementTree來解析這個檔案,並提取出我需要的景點資訊。
確保已經下載了XML檔案並放在專案目錄中。
import xml.etree.ElementTree as ET
file_path = './ChiyaTrip.xml'
try:
tree = ET.parse(file_path)
root = tree.getroot()
spots = root.findall('.//spot')
tourism_data = []
for spot in spots:
name = spot.find('Name').text if spot.find('Name') is not None else 'N/A'
description = spot.find('Description').text if spot.find('Description') is not None else 'N/A'
address = spot.find('Address').text if spot.find('Address') is not None else 'N/A'
tourism_data.append({
'name': name,
'description': description,
'address': address
})
print(f"成功解析 {len(tourism_data)} 筆資料,前三筆如下:\n")
for item in tourism_data[:3]:
print(f"景點名稱: {item['name']}")
print(f"景點描述: {item['description'][:50]}...")
print(f"地址: {item['address']}\n")
這段程式碼會先解析XML檔案並且尋找所有名為spot的元素,建立一個列表儲存資料,從子元素中提取資料,使用 .find().text 安全地取得內容,將提取的資料儲存為字典格式,最後印出前三筆資料作為驗證。
透過這個方法,我們就能將大量的XML資料轉換成Python字典列表,為後續的向量化和RAG流程做好準備。
明天,我們會了解如何將這些整理好的資料,切分並且向量化,塞進 FAISS 知識庫中,謝謝各位今天的觀看。