我正在使用 minted 在我的文档中显示源代码,如下所示:
\section{Image functions}
\inputminted{python}{src/imagefuncs.py}
\section{Matrix operations}
\inputminted{python}{src/matrices.py}
\section{Block operations}
\inputminted{python}{src/blocks.py}
等等,针对多个文件。有没有办法计算这些文件中的行数并输出总数。
Python伪代码:
paths = ['src.py', 'matrices.py', 'blocks.py']
total = 0
for path in paths:
total += linecount(path)
print(str(total))
我发现的任何类似问题都只针对列表并且只有一个文件。
编辑:说清楚点,我想在 latex 中做到这一点,python 代码只是为了说明。
答案1
您可以添加一个键,我将其调用addlines
到\inputminted
您想要的命令中,以处理总行数。
\begin{filecontents*}{test1.py}
paths = ['src.py', 'matrices.py', 'blocks.py']
total = 0
for path in paths:
total += linecount(path)
print(str(total))
\end{filecontents*}
\begin{filecontents*}{test2.py}
paths = ['src.py', 'matrices.py', 'blocks.py']
total = 0
\end{filecontents*}
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{minted}
\usepackage{xpatch}
\makeatletter
\define@key{minted@opt@cmd}{addlines}[true]{\csname @addlines#1\endcsname}
\xpatchcmd{\inputminted}
{\endgroup}
{\if@addlines\addtocounter{totallines}{\value{FancyVerbLine}}\fi\endgroup}
{}{}
\newif\if@addlines
\newcounter{totallines}
\makeatother
\begin{document}
\inputminted[addlines]{python}{test1.py}
\inputminted[addlines]{python}{test2.py}
The total number of code lines is \thetotallines
\end{document}
答案2
以下代码将打印代码清单和行数(全局)。请注意,这绝对不是最有效的方法。
% arara: pdflatex: { shell: 1 }
%!TeX TS-program=arara
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{minted}
\usepackage{expl3,xparse}
\begin{filecontents*}{test1.py}
paths = ['src.py', 'matrices.py', 'blocks.py']
total = 0
for path in paths:
total += linecount(path)
print(str(total))
\end{filecontents*}
\begin{filecontents*}{test2.py}
paths = ['src.py', 'matrices.py', 'blocks.py']
total = 0
\end{filecontents*}
\ExplSyntaxOn
\int_new:N \g__ole_lines_int
\cs_new_nopar:Npn \__ole_countlines:n #1
{
\ior_open:Nn \g_tmpa_ior { #1 }
\ior_str_map_inline:Nn \g_tmpa_ior
{ \int_gincr:N \g__ole_lines_int }
\ior_close:N \g_tmpa_ior
}
\NewDocumentCommand { \inputcode } { m }
{
\inputminted { python } { #1 }
\__ole_countlines:n { #1 }
}
\NewDocumentCommand { \showlines } { }
{
\int_use:N \g__ole_lines_int
}
\ExplSyntaxOff
\begin{document}
\inputcode{test1.py}
\showlines
\inputcode{test2.py}
\showlines
\end{document}