我有一個 CSV 文件,使用“@”作為分隔符,包含以下數據:
Code @ Title @ Page @ Tags @ File
001 @ Buying Tips @ 1 @ seafood, fish, octopus @ 1.pdf
001 @ Buying Tips @ 2 @ oranges, apples @ 2.pdf
001 @ Buying Tips @ 3 @ bananas @ 3.pdf
002 @ Food Waste @ 1 @ compost, apples @ 4.pdf
002 @ Food Waste @ 2 @ plastic, paper, bags @ 5.pdf
我需要從 CSV 檔案中呼叫特定數據,要么顯示在特定行中找到的信息,要么顯示最後一列中列出的文件。
範例可能是:
- 顯示代碼 002 的第 1 頁(將顯示 4.pdf)。
- 顯示所有帶有標籤「apples」的頁面(將顯示 2.pdf 和 4.pdf)。
- 僅顯示 CSV 中第二個出現的「apples」標籤的項目(將顯示 4.pdf)。
- 顯示第 2 頁的標題,代碼 1(將顯示「購買提示」)。
ConTeXt 是否有任何方法可以從 CSV 檔案中以這種方式呼叫資料?
答案1
您可以使用 ConTeXt 內建的 .csv 檔案解析 CSV 檔案的內容rfc4180splitter
。然後可以使用一些 Lua 程式碼輕鬆實現您給出的範例。在這裡,我展示了解析器的用法,以幫助您入門。中還發現了更多解析器util-prs.lua
,你絕對應該看看。
\startbuffer[csv]
Code @ Title @ Page @ Tags @ File
001 @ Buying Tips @ 1 @ seafood, fish, octopus @ 1.pdf
001 @ Buying Tips @ 2 @ oranges, apples @ 2.pdf
001 @ Buying Tips @ 3 @ bananas @ 3.pdf
002 @ Food Waste @ 1 @ compost, apples @ 4.pdf
002 @ Food Waste @ 2 @ plastic, paper, bags @ 5.pdf
\stopbuffer
\startluacode
local csvsplitter = utilities.parsers.rfc4180splitter{separator = "@"}
local rows, colnames = csvsplitter(buffers.getcontent"csv", true)
-- Show what has been parsed on the terminal
inspect(rows)
inspect(colnames)
-- Now pick data and process to your liking
-- ...
\stopluacode
\starttext
\stoptext
在終端機上你會看到
table={
{ "001 ", " Buying Tips ", " 1 ", " seafood, fish, octopus ", " 1.pdf" },
{ "001 ", " Buying Tips ", " 2 ", " oranges, apples ", " 2.pdf" },
{ "001 ", " Buying Tips ", " 3 ", " bananas ", " 3.pdf" },
{ "002 ", " Food Waste ", " 1 ", " compost, apples ", " 4.pdf" },
{ "002 ", " Food Waste ", " 2 ", " plastic, paper, bags ", " 5.pdf" },
}
table={
"Code ",
" Title ",
" Page ",
" Tags ",
" File",
}