我有两个 csv 文件。我想使用第一个 (countries.csv) 生成部分,然后按部分名称过滤第二个 (bottles.csv)。下面是一个 MWE - 您可以看到嵌套文件已正确读取,但 csvsimple 不会继续读取父文件的下一行(仅读取“阿根廷”)。我还包含带有过滤的示例,这似乎表明,一旦读取嵌套 CSV,父 CSV 的其他所有内容都会被遗忘。
如何嵌套(循环?)两个不同的表并应用过滤器?
谢谢!
\documentclass{article}
\usepackage{filecontents}
\usepackage{csvsimple}
\begin{filecontents*}{countries.csv}
country
Argentina
Belgium
\end{filecontents*}
\begin{filecontents*}{bottles.csv}
bottlename, bottlecountry
Bottle A1, Argentina
Bottle B1, Belgium
Bottle A2, Argentina
Bottle C1, China
\end{filecontents*}
\begin{document}
Table of countries.csv (Parent)\\
\csvreader[head to column names]{countries.csv}{}{%
\country\\
}
Table of bottles.csv (Child)\\
\csvreader[head to column names]{bottles.csv}{}{%
\bottlename \bottlecountry\\
}
Table of bottles nested in table of countries. Parent file is not read after \emph{Argentina}\\
\csvreader[head to column names]{countries.csv}{}{%
\section{\country}
\csvreader[head to column names]{bottles.csv}{}{%
\bottlename \bottlecountry\\
}
}
Table of bottles nested in table of countries, with filtering (manually chose "Argentina")\\
\csvreader[head to column names]{countries.csv}{}{%
\section{\country}
\csvreader[filter equal={\bottlecountry}{Argentina},head to column names]{bottles.csv}{}{%
\bottlename \bottlecountry\\
}
}
Table of bottles nested in table of countries, with filtering. Does not remember the country from the parent file.\\
\csvreader[head to column names]{countries.csv}{}{%
\section{\country}
\csvreader[filter equal={\bottlecountry}{\country},head to column names]{bottles.csv}{}{%
\bottlename \bottlecountry\\
}
}
\end{document}
答案1
首先,你不能将 嵌套\csvreader
到另一个 中\csvreader
。但是,你可以读取国家,记住它们,然后读取瓶子。
在我的以下建议中,我使用包中的列表功能etoolbox
将国家名称存储到 中\countrylist
。接下来,我们使用 循环遍历此列表,\dolistloop
该列表本身使用\do
宏。该\do
宏包含瓶子的读数:
\documentclass{article}
\usepackage{filecontents}
\usepackage{csvsimple}
\usepackage{etoolbox}
\begin{filecontents*}{countries.csv}
country
Argentina
Belgium
\end{filecontents*}
\begin{filecontents*}{bottles.csv}
bottlename, bottlecountry
Bottle A1, Argentina
Bottle B1, Belgium
Bottle A2, Argentina
Bottle C1, China
\end{filecontents*}
\begin{document}
\csvreader[head to column names]{countries.csv}{}{%
\listeadd{\countrylist}{\country}%
}
\renewcommand*{\do}[1]{%
\section{#1}%
\csvreader[filter equal={\bottlecountry}{#1},head to column names]{bottles.csv}{}{%
\bottlename\ (from \bottlecountry)\\
}%
}
\dolistloop{\countrylist}
\end{document}