3

I have a word count command in Latex that works well, based on the code here. However, I want the output number to be comma separated for thousands (e.g., 1,000 instead of 1000). I have tried using \numprint and \siunitx but they give me errors, presumably because they can only be applied to a number and not a command. Here is my code:

\documentclass{article}

\usepackage{verbatim}
\usepackage{lipsum}

\newcommand{\quickwordcount}[1]{%
  \immediate\write18{texcount -0 -sum -merge -q #1.tex > #1-words.sum}%
  \input{#1-words.sum}%
}

\begin{document}

There are \quickwordcount{main}words in this document.

\end{document}

Of course, in this example there are only 6 words, but I didn't want to add 1,000 words just to show that it says "1000". How can I show the output with comma separators for thousands?

2
  • 1
    @JasperHabicht No, sorry. It works to use \usepackage{siunitx} and then \num[group-separator={,}]{12345}, which gives "12,345". But \num[group-separator={,}]{\quickwordcount{main}} gives an error. Jun 16, 2023 at 15:53
  • Sorry, I first thought that the linked solution did not work anymore due to a syntax change, but this is actually not true. It does work. See the edit to my answer. Jun 16, 2023 at 16:25

1 Answer 1

3

I think you should be able to use a solution as suggested here:

\documentclass{article}
\usepackage{siunitx}

\ExplSyntaxOn
\NewDocumentCommand { \quickwordcount } { O{} m } {
    \immediate\write18{texcount ~ -0 ~ -sum ~ -merge ~ -q ~ #2.tex ~ > ~ #2-words.sum}
    \file_get:nnN { #2-words.sum } { } \l_tmpa_tl
    \num[#1]{ \l_tmpa_tl }
}
\ExplSyntaxOff

\begin{document}

There are \quickwordcount[group-separator={,}, group-minimum-digits=4]{main} words in this document.

\end{document}

The following solution should also work:

\documentclass{article}
\usepackage{siunitx}

\ExplSyntaxOn
\NewDocumentCommand { \quickwordcount } { O{} m } {
    \immediate\write18{texcount ~ -0 ~ -sum ~ -merge ~ -q ~ #2.tex ~ > ~ #2-words.sum}
    \ior_open:Nn \g_tmpa_ior { #2-words.sum }
    \ior_str_get:NN \g_tmpa_ior \l_tmpa_tl
    \num[#1]{ \l_tmpa_tl }
    \ior_close:N \g_tmpa_ior
}
\ExplSyntaxOff

\begin{document}

There are \quickwordcount[group-separator={,}, group-minimum-digits=4]{main} words in this document.

\end{document}

enter image description here

Note that you would not count words generated with something like \lipsum, because texcount is not able to expand TeX macros.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .