除了一些标记之外,lstlisting在python脚本上看起来工作得很好。根据我的经验,符号"-“和"*”被替换为其他的东西,形状非常相似,但不同。因此,报告到pdf文件中的脚本不能工作。这就是我们要处理的问题。
在这里,我们将使用一个简单的示例代码来处理这个问题:
\documentclass{article}
\usepackage{listings}
\begin{document}
\lstset{language=Python}
\lstset{frame=lines}
\lstset{caption={Insert code directly in your document}}
\lstset{label={lst:code_direct}}
\lstset{basicstyle=\footnotesize}
%\lstset{keepspaces=true}
\lstset{columns=fullflexible}
\begin{lstlisting}
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.01)
y = np.sin(np.pi*x)/(np.pi*x)
plt.plot(x, y)
\end{lstlisting}
\end{document}当我运行它时,会生成一个pdf文件,它看起来很棒。
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(−3, 3, 0.01)
y = np.sin(np.pi∗x)/(np.pi∗x)
plt.plot(x, y)但是,如果我试图将这段代码复制并粘贴到Python整数上,我就会意识到它不起作用,因为"*“和"-”被替换为其他的东西,形状非常相似,但不同。你能帮我修一下吗?
发布于 2022-06-05 00:08:14
我不太清楚为什么会这样..。你能把你的序言加到代码里吗?特别是,我想知道您使用的是什么编码(inutenc)。
不知道为什么清单会这样做,但我发现了一个literate选项,它允许指定清单中应该替换的字符。在本例中,我将减号替换为减号,这似乎阻止了其他代码将其替换为不同的字符。(我总是有一个等号。)
这对我来说很管用:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\begin{document}
\lstset{language=Python, literate={-}{-}1}
\lstset{frame=lines}
\lstset{caption={Insert code directly in your document}}
\lstset{label={lst:code_direct}}
\lstset{basicstyle=\footnotesize}
\lstset{keepspaces=true}
\lstset{columns=fullflexible}
\begin{lstlisting}
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.01)
y = np.sin(np.pi*x)/(np.pi*x)
plt.plot(x, y)
\end{lstlisting}
\end{document}发布于 2022-06-05 08:19:29
正如所建议的那样,这个问题的解决办法是使清单不取代某些特定的标志,在这种情况下,是"*“和"-”。这意味着代码行
\lstset{language=Python}需要用
\lstset{language=Python, literate={symbol_1}{symbol_l}1 {symbol_2}{simbol_2}1 }我们假设有两个符号在某些方面被错误地替换:"symbol_1“和"symbol_2”
因此,为了让Latex示例代码生成一个具有完全工作的Python代码的pdf,需要用以下内容替换以前的示例代码:
\documentclass{article}
\usepackage{listings}
\begin{document}
\lstset{language=Python, literate={-}{-}1 {*}{*}1}
\lstset{frame=lines}
\lstset{caption={Insert code directly in your document}}
\lstset{label={lst:code_direct}}
\lstset{basicstyle=\footnotesize}
%\lstset{keepspaces=true}
\lstset{columns=fullflexible}
\begin{lstlisting}
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.01)
y = np.sin(np.pi*x)/(np.pi*x)
plt.plot(x, y)
\end{lstlisting}
\end{document}我并不保证它对每个Python代码都有效,但是每次您测试Python代码或类似的、从Latex生成的脚本中复制和粘贴的Python代码时,您都可以像前面一样,通过添加literate={symbol_x}{symbol_x}1来修复传入的bug。
https://stackoverflow.com/questions/72503522
复制相似问题