將單字加入 Python 語言的 lstlisting 中

將單字加入 Python 語言的 lstlisting 中

我希望在插入 LaTeX 文件的一些 python 程式碼中添加一些關鍵字。我想讓True&False顯示為黃色,並且一些模組調用如ttk顯示為紅色。我嘗試過使用 morekeywords 調用,但是,它對我不起作用。下面是我的 LaTeX 程式碼:

\newcommand\pythonstyle{\lstset{
language=Python,
basicstyle=\ttm,
otherkeywords={self},             
keywordstyle=\ttb\color{deepblue},
morekeywords={ttk}
emph={MyClass,__init__},          
emphstyle=\ttb\color{deepred},    
stringstyle=\color{deepgreen},

showstringspaces=false            
}}

答案1

您可以使用

keywords=[<number>]{<list of keywords>}

另一組關鍵字,然後

keywordstyle={[<number>]<style commands>},

為這個新系列提供一種風格。

由於我沒有顏色的原始定義,也沒有 \ttb 命令的原始定義,因此在下面的示例中我使用了一些自己的設置,但您可以輕鬆使用自己的設置;該程式碼是隨機獲取的,僅用於本範例。

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{bera}% optional; just for the example

\lstset{
language=Python,
basicstyle=\ttfamily,
otherkeywords={self},             
keywordstyle=\ttfamily\color{blue!90!black},
keywords=[2]{True,False},
keywords=[3]{ttk},
keywordstyle={[2]\ttfamily\color{yellow!80!orange}},
keywordstyle={[3]\ttfamily\color{red!80!orange}},
emph={MyClass,__init__},          
emphstyle=\ttfamily\color{red!80!black},    
stringstyle=\color{green!80!black},
showstringspaces=false            
}

\begin{document}

\begin{lstlisting} 
def under_attack(col, queens):
    left = right = col
    for r, c in reversed(queens):
        left, right = left - 1, right + 1

        if c in (left, col, right):
            return True
    return False
    print 'This generation has {0} babies'.format(babies)
ttk.Button(buttonframe,width = 3,
           textvariable=guivars["%s %s" %(current, item)],
           command=lambda: remoteButton(current, item))
\end{lstlisting}

\end{document}

在此輸入影像描述

請注意,“ttk”被視為紅色關鍵字,正如所要求的那樣。

相關內容