LangChain 中有幾十個文件載入器,可以在這檢視https://python.langchain.com/v0.2/docs/integrations/document_loaders
但是實際使用過程中,這些解析的效果層次補齊,需要結合自己的檔去寫如何載入具體文件。這個也是在後續開發框架的過程中,我們可以選取langchian的document作為處理物件,但是檔解析需要自己去寫和實作。
在本章中,我們將介紹其中的一些:
TextLoader
CSVLoader
UnstructuredFileLoader
DirectoryLoader
UnstructuredHTMLLoader
JSONLoader
PyPDFLoader
ArxivLoader
Docx2txtLoader
unset unset TextLoader unset unset
from langchain_community.document_loaders import TextLoader
loader = TextLoader("text.txt")
loader.load()
"""
[Document(page_content='I have some instructions here.\nThis is the second row.', metadata={'source': 'text.txt'})]
"""
loader = TextLoader("index.md")
loader.load()
"""
[Document(page_content='some instructions\n', metadata={'source': 'index.md'})]
"""
unset unset CSVLoader unset unset
import pandas as pd
# Create a simple DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# Export the DataFrame to a CSV file
csv_file_path = 'sample_data.csv'
df.to_csv(csv_file_path, index=False)
from langchain_community.document_loaders.csv_loader import CSVLoader
loader = CSVLoader(file_path='sample_data.csv')
data = loader.load()
data
"""
[Document(page_content='Name: Alice\nAge: 25\nCity: New York', metadata={'source': 'sample_data.csv', 'row': 0}),
Document(page_content='Name: Bob\nAge: 30\nCity: Los Angeles', metadata={'source': 'sample_data.csv', 'row': 1}),
Document(page_content='Name: Charlie\nAge: 35\nCity: Chicago', metadata={'source': 'sample_data.csv', 'row': 2})]
"""
如有必要,我們可以在讀取檔時自訂 CSV 參數:
loader = CSVLoader(file_path='sample_data.csv', csv_args={
'delimiter': ',',
'quotechar': '"',
'fieldnames': ['Name', 'Age', 'City']
})
data = loader.load()
data
# now the headers are also a row.
"""
[Document(page_content='Name: Name\nAge: Age\nCity: City', metadata={'source': 'sample_data.csv', 'row': 0}),
Document(page_content='Name: Alice\nAge: 25\nCity: New York', metadata={'source': 'sample_data.csv', 'row': 1}),
Document(page_content='Name: Bob\nAge: 30\nCity: Los Angeles', metadata={'source': 'sample_data.csv', 'row': 2}),
Document(page_content='Name: Charlie\nAge: 35\nCity: Chicago', metadata={'source': 'sample_data.csv', 'row': 3})]
"""
當從 CSV 檔載入數據時,載入器通常會為 CSV 中的每一行數據建立一個單獨的「文件」物件。
預設情況下,每個文件的來源都設定為 CSV 本身的整個檔路徑。如果想跟蹤 CSV 中每條資訊的來源,這可能並不理想。
可以使用 source_column 指定 CSV 檔中的列名。然後,每行特定列中的值將用作從該行建立的相應文件的單獨來源
loader = CSVLoader(file_path='sample_data.csv', source_column="Name")
data = loader.load()
data
"""
[Document(page_content='Name: Alice\nAge: 25\nCity: New York',
metadata={'source': 'Alice', 'row': 0}),
Document(page_content='Name: Bob\nAge: 30\nCity: Los Angeles',
metadata={'source': 'Bob', 'row': 1}),
Document(page_content='Name: Charlie\nAge: 35\nCity: Chicago',
metadata={'source': 'Charlie', 'row': 2})]
"""
這在使用涉及根據資訊來源回答問題的「鏈」(可能是數據處理管道)時特別有用。透過為每個文件提供單獨的源資訊,這些鏈可以在處理時考慮數據的來源,並可能提供更細致入微或更可靠的答案。
unset unset UnstructuredCSVLoader unset unset
與
CSVLoader
不同,
CSVLoader
將每一行視為一個單獨的文件,並使用標題定義數據,而在
UnstructuredCSVLoader
中,整個 CSV 檔被視為單個「非結構化表」元素。當您想要將數據作為整個表而不是單個條目進行分析時,這很有用。
from langchain_community.document_loaders.csv_loader import UnstructuredCSVLoader
loader = UnstructuredCSVLoader(
file_path="sample_data.csv", mode="elements"
)
docs = loader.load()
docs
"""
[Document(page_content='\n\n\nName\nAge\nCity\n\n\nAlice\n25\nNew York\n\n\nBob\n30\nLos Angeles\n\n\nCharlie\n35\nChicago\n\n\n', metadata={'source': 'sample_data.csv', 'filename': 'sample_data.csv', 'languages': ['eng'], 'last_modified': '2024-03-04T18:05:41', 'text_as_html': '<table border="1" class="dataframe">\n <tbody>\n <tr>\n <td>Name</td>\n <td>Age</td>\n <td>City</td>\n </tr>\n <tr>\n <td>Alice</td>\n <td>25</td>\n <td>New York</td>\n </tr>\n <tr>\n <td>Bob</td>\n <td>30</td>\n <td>Los Angeles</td>\n </tr>\n <tr>\n <td>Charlie</td>\n <td>35</td>\n <td>Chicago</td>\n </tr>\n </tbody>\n</table>', 'filetype': 'text/csv', 'category': 'Table'})]
"""
如果在「元素」模式下操作,則表的 HTML 表示將可在後設資料中存取。
print(docs[0].metadata["text_as_html"])
"""
<table border="1" class="dataframe">
<tbody>
<tr>
<td>Name</td>
<td>Age</td>
<td>City</td>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
<td>Los Angeles</td>
</tr>
<tr>
<td>Charlie</td>
<td>35</td>
<td>Chicago</td>
</tr>
</tbody>
</table>
"""
unset unset UnstructuredFileLoader unset unset
與
TextLoader
等專為特定格式設計的載入器不同,
UnstructuredFileLoader
會自動檢測您提供的檔型別。
載入器利用了底層的「unstructured」庫。該庫會分析檔內容並嘗試根據檔型別提取有意義的資訊。
from langchain_community.document_loaders import UnstructuredFileLoader
loader = UnstructuredFileLoader("text.txt")
docs = loader.load()
docs
"""
[Document(page_content='I have some instructions here.\n\nThis is the second row.', metadata={'source': 'text.txt'})]
"""
loader = UnstructuredFileLoader(
"text.txt", mode="elements"
)
docs = loader.load()
docs
"""
[Document(page_content='I have some instructions here.', metadata={'source': 'text.txt', 'filename': 'text.txt', 'last_modified': '2024-03-04T18:15:12', 'languages': ['eng'], 'filetype': 'text/plain', 'category': 'NarrativeText'}),
Document(page_content='This is the second row.', metadata={'source': 'text.txt', 'filename': 'text.txt', 'last_modified': '2024-03-04T18:15:12', 'languages': ['eng'], 'filetype': 'text/plain', 'category': 'NarrativeText'})]
"""
loader = UnstructuredFileLoader("your_report.html")
docs = loader.load()
docs
"""
[Document(page_content='Toggle navigation\n\nPandas Profiling Report\n\nOverview\n\nVariables\n\nInteractions\n\nCorrelations\n\nMissing values\n\nSample\n\nOverview\n\nOverview\n\nAlerts 44\n\nReproduction\n\nDataset statistics\n\nNumber of variables 44 Number of observations 58592 Missing cells 0 Missing cells (%) 0.0% Duplicate rows 0 Duplicate rows (%) 0.0% Total size in memory 19.7 MiB Average record size in memory 352.0 B\n\nVariable types\n\nText 1 Numeric 10 Categorical 16 Boolean 17\n\nairbags is highly overall correlated with cylinder and 28 other fields High correlation cylinder is highly overall correlated with airbags and 22 other fields High correlation displacement is highly overall correlated with airbags and 33 other fields High correlation engine_type is highly overall correlated with airbags and 30 other fields High correlation fuel_type is highly overall correlated with airbags and 30 other fields High correlation gear_box is highly overall correlated with airbags and 23 other fields High correlation gross_weight is highly overall correlated with airbags and 32 other fields High correlation height is highly overall correla
"""
# pip install "unstructured[pdf]"
loader = UnstructuredFileLoader("ticket.pdf")
docs = loader.load()
docs
"""
[Document(page_content='Event\n\nCommence Date\n\nReference\n\nPaul Kalkbrenner\n\n10 September,Satu
[email protected]', metadata={'source': 'ticket.pdf'})]
"""
unset unset DirectoryLoader unset unset
DirectoryLoader
可幫助一次性從整個目錄載入多個文件。它利用了
UnstructuredFileLoader
。
from langchain_community.document_loaders import DirectoryLoader
loader = DirectoryLoader('folder/')
docs = loader.load()
print(len(docs)) # 3
# we can declare extension, display progress bar, use multithreading
loader = DirectoryLoader('folder/', glob="*.txt", show_progress=True, use_multithreading=True)
docs = loader.load()
print(len(docs)) # 1
unset unset UnstructuredHTMLLoader unset unset
它利用「非結構化」庫的功能從儲存為 HTML 檔的網頁中提取有意義的內容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>A div element</div>
<p>a p element</p>
<div>
<p>a p inside of a div</p>
</div>
</body>
</html
from langchain_community.document_loaders import UnstructuredHTMLLoader
loader = UnstructuredHTMLLoader("index.html")
data = loader.load()
data
"""
[Document(page_content='A div element\n\na p element\n\na p inside of a div', metadata={'source': 'index.html'})]
"""
我們可以使用
BeautifulSoup4
透過
BSHTMLLoader
來解析 HTML 文件。
from langchain_community.document_loaders import BSHTMLLoader
loader = BSHTMLLoader("index.html")
data = loader.load()
data
"""
[Document(page_content='\n\n\n\nDocument\n\n\nA div element\na p element\n\na p inside of a div\n\n\n\n', metadata={'source': 'index.html', 'title': 'Document'})]
"""
unset unset JSONLoader unset unset
JSONLoader 被設計用於處理以 JSON 形式儲存的數據。
[
{
"id": 1,
"name": "John Doe",
"email": "[email protected]",
"age": 30,
"city": "New York"
},
{
"id": 2,
"name": "Jane Smith",
"email": "[email protected]",
"age": 25,
"city": "Los Angeles"
},
{
"id": 3,
"name": "Alice Johnson",
"email": "[email protected]",
"age": 28,
"city": "Chicago"
}
]
JSONLoaders
利用 JQ 庫來解析 JSON 數據。JQ 提供了一種專為處理 JSON 結構而設計的強大查詢語言。
jq_schema
參數允許在 JSONLoader 函式中提供 JQ 運算式。
from langchain_community.document_loaders import JSONLoader
loader = JSONLoader(
file_path='example.json',
jq_schema='map({ name, email })',
text_content=False)
data = loader.load()
data
"""
[Document(page_content="[{'name': 'John Doe', 'email': '[email protected]'},
{'name': 'Jane Smith', 'email': '[email protected]'}, {'name': 'Alice Johnson', 'email': '[email protected]'}]", metadata={'source': '/Users/okanyenigun/Desktop/codes/python__general/example.json', 'seq_num': 1})]
"""
JSON 行檔是一個文字檔案,其中每行都是一個有效的 JSON 物件,由換行符分隔。
{"name": "John Doe", "age": 30}
{"name": "Jane Smith", "age": 25}
{"name": "Alice Johnson", "age": 28}
loader = JSONLoader(
file_path='example.jsonl',
jq_schema='.content',
text_content=False,
json_lines=True)
data = loader.load()
from pprint import pprint
pprint(data)
"""
[Document(page_content='', metadata={'source': '/Users/okanyenigun/Desktop/codes/python__general/example.jsonl', 'seq_num': 1}),
Document(page_content='', metadata={'source': '/Users/okanyenigun/Desktop/codes/python__general/example.jsonl', 'seq_num': 2}),
Document(page_content='', metadata={'source': '/Users/okanyenigun/Desktop/codes/python__general/example.jsonl', 'seq_num': 3})]
"""
unset unset PyPDFLoader unset unset
它利用 pypdf 庫來載入 PDF 檔。
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("ticket.pdf")
pages = loader.load_and_split()
pages[0]
"""
Document(page_content='Paul Kalkbrenner\nThis electronically generated document will grant you entry to the event and time specified on this ticket. The security of the ticket belongs to the\nowner
...
Sarıyer, İstanbul', metadata={'source': 'ticket.pdf', 'page': 0})
"""
我們還可以使用 UnstructuredPDFLoader 來載入 PDF。
from langchain_community.document_loaders import UnstructuredPDFLoader
loader = UnstructuredPDFLoader("ticket.pdf")
data = loader.load()
我們有 OnlinePDFLoader 來載入線上 PDF。
from langchain_community.document_loaders import OnlinePDFLoader
loader = OnlinePDFLoader("https://arxiv.org/pdf/2302.03803.pdf")
data = loader.load()
data
"""
[Document(page_content='3 2 0 2\n\nb e F 7\n\n]\n\nG A . h t a m\n\n[\n\n1 v 3 0 8 3 0 . 2 0 3 2 : v i X r a\n\nA WEAK (k, k)-LEFSCHETZ THEOREM FOR PROJECTIVE TORIC ORBI...
"""
還有更多利用不同來源的……
# PyPDFium2Loader
from langchain_community.document_loaders import PyPDFium2Loader
loader = PyPDFium2Loader("ticket.pdf")
data = loader.load()
# PDFMinerLoader
from langchain_community.document_loaders import PDFMinerLoader
loader = PDFMinerLoader("ticket.pdf")
data = loader.load()
# PDFMinerPDFasHTMLLoader
from langchain_community.document_loaders import PDFMinerPDFasHTMLLoader
loader = PDFMinerPDFasHTMLLoader("ticket.pdf")
data = loader.load()[0] # entire PDF is loaded as a single Document
# PyMuPDFLoader
from langchain_community.document_loaders import PyMuPDFLoader
loader = PyMuPDFLoader("ticket.pdf")
data = loader.load()
# Directory loader for PDF
from langchain_community.document_loaders import PyPDFDirectoryLoader
loader = PyPDFDirectoryLoader("folder/")
docs = loader.load()
unset unset ArxivLoader unset unset
它旨在從 arXiv 開放存取庫中獲取和處理文件。
# pip install arxiv
from langchain_community.document_loaders import ArxivLoader
docs = ArxivLoader(query="1605.08386", load_max_docs=2).load()
print(len(docs))
print()
print(docs[0].metadata)
"""
1
{'Published': '2016-05-26', 'Title': 'Heat-bath random walks with Markov
bases', 'Authors': 'Caprice Stanley, Tobias Windisch', 'Summary':
'Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.'}
"""
unset unset Docx2txtLoader unset unset
它適用於 Microsoft Office Word 文件。
from langchain_community.document_loaders import Docx2txtLoader
loader = Docx2txtLoader("example_data/fake.docx")
data = loader.load()
data
"""
[Document(page_content='Lorem ipsum dolor sit amet.',
metadata={'source': 'ex...
"""