如何在 ConTeXt 中调用 CSV 中的特定数据行?

如何在 ConTeXt 中调用 CSV 中的特定数据行?

我有一个 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”的第 2 个出现的项目(将显示 4.pdf)。
  • 显示第 2 页的标题,代码 1(显示“购买提示”)。

ConTeXt 是否有任何方法可以以这种方式从 CSV 文件中调用数据?

答案1

您可以使用 ConTeXt 内置的 来解析 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",
}

相关内容