\docsvlist 和嵌套函数:不需要的大空格

\docsvlist 和嵌套函数:不需要的大空格

我想遍历逗号分隔的列表来翻译一些单词。我已经找到了如何使用包\docsvlist中的命令来做到这etoolbox一点。但是,在第一个单词之前和单词之间打印了一个很大的空格,而打印的逗号后应该只有一个“正常”的空格。我认为问题出在\ifstrequal用于翻译的命令的嵌套上。

下面是一个 MWE,其中包括一个调用所有可能的翻译的示例和另一个仅调用第一个翻译的示例,以显示嵌套的影响。

我怎样才能避免这些额外的空格?

平均能量损失

\documentclass{article}

\usepackage{etoolbox}

\begin{document}
    
    \newcommand\TranslateAnimal[1]{
        \ifstrequal{#1}{Cat}{Chat}{
            \ifstrequal{#1}{Dog}{Chien}{
                \ifstrequal{#1}{Mouse}{Souris}{
                    \ifstrequal{#1}{Bird}{Oiseau}{
                        \ifstrequal{#1}{Horse}{Cheval}{
                            #1 % If there is no known translation
        }}}}}
    }

    \newcommand{\TranslateAnimalList}[2][,]{
        \def\nextitem{\def\nextitem{#1}}% Separator
        \renewcommand*{\do}[1]{\nextitem\TranslateAnimal{##1}} % How to process each item
        \docsvlist{#2}% Process list
    }

    There are additional large spaces before the first word and after words: \TranslateAnimalList{Cat,Bird,Dog,Horse,Mouse,Seal,Donkey}
    
    Compare with: \TranslateAnimalList{Cat,Cat,Cat,Cat,Cat,Cat,Cat} where there is only a large space before the first word

\end{document}

答案1

检查差异并查看行尾的百分号 (%) 有什么用?(为什么我的宏会产生额外的空间?)

\documentclass{article}

\usepackage{etoolbox}

\newcommand\TranslateAnimal[1]{%
  \ifstrequal{#1}{Cat}{Chat}{%
    \ifstrequal{#1}{Dog}{Chien}{%
      \ifstrequal{#1}{Mouse}{Souris}{%
        \ifstrequal{#1}{Bird}{Oiseau}{%
          \ifstrequal{#1}{Horse}{Cheval}{%
            #1% If there is no known translation
  }}}}}%
}

\newcommand{\TranslateAnimalList}[2][, ]{%
  \def\nextitem{\def\nextitem{#1}}% Separator
  \renewcommand*{\do}[1]{\nextitem\TranslateAnimal{##1}}% How to process each item
  \docsvlist{#2}% Process list
}

\begin{document}
    
The list is \TranslateAnimalList{Cat,Bird,Dog,Horse,Mouse,Seal,Donkey}.

Compare with \TranslateAnimalList{Cat,Cat,Cat,Cat,Cat,Cat,Cat}.

\end{document}

您可能会欣赏到不同的实现方式expl3

\documentclass{article}
%\usepackage{xparse} % not needed with LaTeX 2020-10-01 or later

\ExplSyntaxOn
\NewExpandableDocumentCommand{\TranslateAnimal}{m}
 {
  \str_case:nnF { #1 }
   {
    {Cat}{Chat}
    {Dog}{Chien}
    {Mouse}{Souris}
    {Bird}{Oiseau}
    {Horse}{Cheval}
   }
   { #1 } % no known translation
 }

\NewDocumentCommand{\TranslateAnimalList}{O{,~}m}
 {
  \seq_clear:N \l_tmpa_seq
  \clist_map_inline:nn { #2 }
   {
    \seq_put_right:Nn \l_tmpa_seq { \TranslateAnimal { ##1 } }
   }
  \seq_use:Nn \l_tmpa_seq { #1 }
 }
\ExplSyntaxOff

\begin{document}
    
The list is \TranslateAnimalList{Cat,Bird,Dog,Horse,Mouse,Seal,Donkey}.

Compare with \TranslateAnimalList{Cat,Cat,Cat,Cat,Cat,Cat,Cat}.

\end{document}

在此处输入图片描述

相关内容