是否可以将文件中的项目导入到 itemize 环境中?例如,考虑一个只有单词而没有格式的文件:
Elem1
Elem2
Elem3
Elem4
...
Elem120933
我喜欢读取这个文件并将其放在itemize
,enumerate
等中。我敢打赌这可以通过宏来完成,但不确定如何处理它。
答案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}