itemize 环境中文件中的项目

itemize 环境中文件中的项目

是否可以将文件中的项目导入到 itemize 环境中?例如,考虑一个只有单词而没有格式的文件:

Elem1
Elem2
Elem3
Elem4
...
Elem120933

我喜欢读取这个文件并将其放在itemizeenumerate等中。我敢打赌这可以通过宏来完成,但不确定如何处理它。

请注意,这是一个来自 StackOverflow 的确切问题,尚未得到解答,并且我对此很感兴趣。

答案1

\documentclass{article}


\newread\myread% Get a file handle grip, call it myread


\newcommand{\openandtypeset}[1]{%
\IfFileExists{#1}{%  Check first
\openin\myread=#1  % Open the file from #1 
\begin{itemize}
\loop
\read\myread to \localvariable   % Read line content to `\localvariable`
\ifeof\myread  % Is it at the end of the file -> localvariable is empty effectively --> do not use \item then
\else
\item \localvariable % Typeset the local item
\repeat
\end{itemize}
\closein\myread%  Close the file. 
}{}% End of \IfFileExists
}

\begin{document}
\openandtypeset{itemfromfile.txt}

\end{document}

这是itemfromfile.txt文件

This is 
a \LaTeXe
list
read
from
file

编辑稍微改进的版本:

\documentclass{article}

\newread\myread% Get a file handle grip called \myread


\newcommand{\loaditemsfromfile}[2][enumerate]{%
\IfFileExists{#2}{%
  \openin\myread=#2
  \begin{#1}  % Use an itemize enviroment with #1 as name of the env. 
    \loop\unless\ifeof\myread%
    \read\myread to \localvariable
    \ifeof\myread
    \else
  \item \localvariable
    \fi
    \repeat
  \end{#1} % close the environment
  \closein\myread%  \close the file
}{}%
}

\begin{document}
\loaditemsfromfile{itemfromfile.txt}

\loaditemsfromfile[itemize]{itemfromfile.txt}

\end{document}

在此处输入图片描述

相关内容