使用 xstring 统计字符数

使用 xstring 统计字符数

我有以下代码,由作者 Christian Tellechea 提供xstring,非常感谢。其思想是计算结构中属于预定义列表的字符数。

\documentclass{article}
\usepackage{xstring}
\usepackage{blindtext}
\makeatletter
\def\countoccurs#1#2{%
    \saveexpandmode\expandarg
    %\exploregroups
    \expandafter\def\expandafter\tmp@list\expandafter{\list,}%
    \let\nboccur\z@
    \loop
        \unless\ifx\empty\tmp@list
            \StrCut\tmp@list,\tmp@cs\tmp@list
            %\StrCount{\noexpand#2}\tmp@cs[\tmp@cs]%
            \StrCount{#2}\tmp@cs[\tmp@cs]%
            \edef\nboccur{\number\numexpr\nboccur+\tmp@cs}%
    \repeat
    \restoreexpandmode
}
%\def\list{12,a,bc,9} % list can also be defined as this
\def\list{%
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,Q,r,s,t,u,v,w,x,y,z,%
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,S,X,Y,Z,%
1,2,3,4,5,6,7,8,9,0,%
}
\def\countenv#1{#1\countoccurs\list{#1}}
\makeatother

\begin{document}
\countenv{\begin{tabular}{ll} a & b \\ a & c \end{tabular}}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\textbf{D}2345}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\blindtext}\par
I counted: \nboccur.

\noindent\hrulefill

%\countoccurs\list{12987d bc abcabc999}
\countenv{12987d bc abcabc999}\par
I counted: \nboccur.

\noindent\hrulefill
\end{document}

正如您在输出中看到的,第一个和最后一个计数是正确的,但其他计数不正确。我尝试使用和,\exploregroups\noexpand#2所有给出的示例都不太好。例如,\noexpand#2纠正了第二个输出,但严重影响了第一个和第三个输出。有没有一种适用于所有情况的方法?

答案1

\blindtext不会扩展到某些文本,但在获得文本之前执行许多(不可扩展的)命令。

您可以尝试使用kantlipsum,它可以定义一个扩展到其某个段落的宏。

\documentclass{article}
\usepackage{xstring}

\usepackage{kantlipsum}
\kantdef\mytext{1}

\makeatletter
\def\countoccurs#1#2{%
    \saveexpandmode\expandarg
    %\exploregroups
    \expandafter\def\expandafter\tmp@list\expandafter{\list,}%
    \let\nboccur\z@
    \loop
        \unless\ifx\empty\tmp@list
            \StrCut\tmp@list,\tmp@cs\tmp@list
            %\StrCount{\noexpand#2}\tmp@cs[\tmp@cs]%
            \StrCount{#2}\tmp@cs[\tmp@cs]%
            \edef\nboccur{\number\numexpr\nboccur+\tmp@cs}%
    \repeat
    \restoreexpandmode
}
%\def\list{12,a,bc,9} % list can also be defined as this
\def\list{%
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,Q,r,s,t,u,v,w,x,y,z,%
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,S,X,Y,Z,%
1,2,3,4,5,6,7,8,9,0,%
}
\def\countenv#1{#1\countoccurs\list{#1}}
\makeatother

\begin{document}
\countenv{\begin{tabular}{ll} a & b \\ a & c \end{tabular}}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\textbf{D}2345}\par
I counted: \nboccur.

\noindent\hrulefill

\countenv{\mytext}\par
I counted: \nboccur.

\noindent\hrulefill

%\countoccurs\list{12987d bc abcabc999}
\countenv{12987d bc abcabc999}\par
I counted: \nboccur.

\noindent\hrulefill
\end{document}

之后长的时间(我的机器上是 15 秒,很长处理时间),你就会得到这个。

在此处输入图片描述

相关内容