Latex for-loop 用于生成表头

Latex for-loop 用于生成表头

在给出的表中这里列重复了。有没有办法在 Latex 中循环这些列,这样就不必手动写出列了?这样表格只会加载前 5 列,而用户无需输入诸如 之类的内容\myhead{\csvcoliv}

\documentclass{article}
\usepackage{csvsimple,array,filecontents,booktabs}

\begin{filecontents*}{forum_posts_table_1.csv}
    posts per author,sentences per post,quoted sentences per post,EREs per post,mentions per ERE
    3.1,23.83454,2313.27,13453453.8,2464642.43
    4.1,23.83454,2313.27,13453453.8,2464642.43
    5.1,23.83454,2313.27,13453453.8,2464642.43
\end{filecontents*}

\begin{document}

\newcommand\myhead[1]{\parbox[t]{5em}{\centering\bfseries#1\par\kern1mm}}

\csvreader[no head,column count=5,tabular=rrrrr,
  table head=\toprule,
  late after first line=\\\midrule,
  table foot=\bottomrule
  ]%
{forum_posts_table_1.csv}{}{%
  \csviffirstrow{\myhead{\csvcoli} & \myhead{\csvcolii} & \myhead{\csvcoliii}
    & \myhead{\csvcoliv} & \myhead{\csvcolv}
    }{\csvlinetotablerow}
}

\end{document}

答案1

经过一段时间的摆弄,我想出了一个解决方案(不使用\loop--\repeat解决方案):

\documentclass{article}
\usepackage{csvsimple,array,filecontents,booktabs}
\usepackage{forloop}

\newcount\loopcount
\loopcount=5
\newcounter{loopiti}

\def\continuefortheglory{%
    &\fortheglory%
}

\def\fortheglory{%
    \stepcounter{loopiti}%
    \myhead{%
        \expandafter\csname csvcol\roman{loopiti}\endcsname%
    }%
    \ifnum\loopcount>\value{loopiti}%
    \expandafter\continuefortheglory%
    \fi%
}


\begin{filecontents*}{forum_posts_table_1.csv}
    posts per author,sentences per post,quoted sentences per post,EREs per post,mentions per ERE
    3.1,23.83454,2313.27,13453453.8,2464642.43
    4.1,23.83454,2313.27,13453453.8,2464642.43
    5.1,23.83454,2313.27,13453453.8,2464642.43
\end{filecontents*}

\begin{document}

\newcommand\myhead[1]{\parbox[t]{5em}{\centering\bfseries#1\par\kern1mm}}

\csvreader[no head,column count=5,tabular=rrrrr,
  table head=\toprule,
  late after first line=\\\midrule,
  table foot=\bottomrule
  ]%
{forum_posts_table_1.csv}{}{%
  \csviffirstrow{\myhead{\csvcoli} & \myhead{\csvcolii} & \myhead{\csvcoliii}
    & \myhead{\csvcoliv} & \myhead{\csvcolv}
    }{\csvlinetotablerow}
}

\vskip5mm
using fortheglory:
\vskip5mm

\setcounter{loopiti}{0}
\csvreader[no head,column count=5,tabular=rrrrr,
  table head=\toprule,
  late after first line=\\\midrule,
  table foot=\bottomrule
  ]%
{forum_posts_table_1.csv}{}{%
    \csviffirstrow{\fortheglory}{\csvlinetotablerow}
}


\end{document}

结果

编辑:使用这个,你必须\loopcount=对每个表使用,它没有与前一个表相同的列数,并且必须\setcounter{loopiti}{0}在每个表之前发出,但你可以将它包含在这样的包装器命令中:

\newcommand{\glorycol}[1]{\loopcount=#1\setcounter{loopiti}{0}\fortheglory}

然后你只需要将它用于一个有 5 列的表格,如下所示:

\csvreader[no head,column count=5,tabular=rrrrr,
  table head=\toprule,
  late after first line=\\\midrule,
  table foot=\bottomrule
  ]%
{forum_posts_table_1.csv}{}{%
    \csviffirstrow{\glorycol{5}}{\csvlinetotablerow}
}

可能有更好的方法(例如自动确定列数并在失败时提供可选参数)但这超出了我的技能(目前,我希望......)。

相关内容