我想将我的 Python 代码放在一个两列文档中。我使用的listings
包具有以下序言:
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=true,
breaklines=true,
captionpos=b,
keepspaces=true,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=mystyle}
我有 .py 文件的 python 代码,并且在正文中使用它,如下所示:
\lstinputlisting[language=Python]{<filename>.py}
但结果却如下图所示。
有没有办法将代码放在边距内?
答案1
以下重新格式化您的代码以轻松适应边距,并且是语法正确的 Python 代码。
\documentclass[twocolumn]{article}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=true,
breaklines=true,
captionpos=b,
keepspaces=true,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=mystyle}
\begin{document}
\begin{lstlisting}
plt.errorbar(delay, TB, np.sqrt(TB/10))
i_max = np.argmax(TB)
print(delay[i_max])
plt.axvline(delay[i_max], linestyle='-',
color='g', label='-2.5')
plt.xlabel('delay (ns)')
plt.ylabel('Coincidence rate (Hz)')
plt.legend()
plt.show()
GRA_coincidence = np.zeros(6)
GRA_coincidence_acc = np.zeros(6)
GRA_SNR = np.zeros(6)
GRA_SNR_error = np.zeros(6)
GRA_RB = np.zeros(6)
GRA_RT = np.zeros(6)
Racc = np.zeros(6)
plt.figure()
for i in range(6):
A = '/content/coinc/coincidence' + \
str(i + 1) + '.csv'
res = read_gra(A)
B = '/content/coinc/accidental' + \
str(i + 1) + '.csv'
res_acc = read_gra(B)
\end{lstlisting}
\end{document}