用列表隱藏 python 註釋

用列表隱藏 python 註釋

我想包含要使用清單格式化的 Python 程式碼,但我只希望程式碼整潔緊湊。不得列印任何註釋,也不得出現空白行。

簡單的方法是去掉程式碼中的註釋,但這是繞過問題並且沒有找到解決方案。我想要一個解決方案。解決方案意味著我不必編輯正在匯入的來源檔案。

我已經嘗試過以下方法:

方法一

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [l][\nullfont]{\#},
    emptylines   = *1,
}

它不會打印註釋,但自從文本到達輸出後,這些行就保留在那裡,只是 LaTeX 用nullfont.

方法2

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [is]{\#}{\^^M},
    emptylines   = *1,
}

#方法 2 忽略從到行尾的所有註解行。問題是,行尾也消失了!假設你有這個程式碼:

def foo():
    if cond1: bar() #Some explanation
    if cond2: baz() #Some other explanation
    if cond3: bye() #Even more explanations

它會印如下:

def foo():
    if cond1: bar()        if cond2: baz()        if cond3: bye()

這是不可取的、不符合Python風格的、而且醜陋的。

方法3

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [il]{\#},
    emptylines   = *1,
}

這個應該像一個魅力一樣工作,但由於某種原因它清除了第一個評論中的所有程式碼(請參閱foo()範例)。

因此我正在尋找其他的東西來嘗試。難道這對於列表來說是不可能的嗎?

提前乾杯並表示感謝。


編輯1:

可以找到MWE這裡

答案1

這是有效的。它涉及一些listings“內部結構”。我不確定是否有更好的解決方案。使用行尾分隔符號(上面的方法 2)並在行不為空時將其加回似乎不起作用。

\documentclass[11pt]{article}
\usepackage{xcolor}
\usepackage{listings}

% Default settings.
\lstset{
  basicstyle=\ttfamily,
  numbers=left,
  numbersep=5pt,
  numberstyle=\tiny\color{gray},
  rulecolor=\color{black},
}

% The \incomment macro and auxiliary stuff.
\newif\ifnocomment
\newif\ifemptyline
\makeatletter
% When a line starts, it's empty and we're not in a comment.
\lst@AddToHook{InitVarsBOL}{\global\emptylinetrue\global\nocommenttrue}
% When something is printed, the line is not empty.
\lst@AddToHook{PostOutput}{\global\emptylinefalse}
% When we're in a comment...
\def\incomment#1{%
  % if we just entered...
  \ifnocomment%
    \global\nocommentfalse%
    % and the line is empty, then remove this line.
    \ifemptyline\global\advance\lst@newlines\m@ne\fi%
  \fi}
\makeatother

\lstdefinestyle{python_without_comments}{%
  language=python,
  morecomment=[l][\incomment]{\#},
}

\begin{document}
\begin{lstlisting}[style=python_without_comments]
def f(x): return x + 1 #

# This is function foo...
def foo():
  if cond1: bar()  # Some explanation
  if cond2: baz()  # Some other explanation
  if cond3: bye()  # Even more explanations

# And this is function bar
def bar():  # let's see
  # some more comment
  return 42 # here?
\end{lstlisting}
\end{document}

結果是: 結果

如果文字中有註釋,它可能會在文字末尾列印一個空白行;我不知道如何刪除它。


編輯:我原來的答案是用 hookOutputBox而不是PostOutput.這對於選項卡來說效果不佳。

相關內容