27

How can I create the environment that could count words inside itself? More specifically, I want to write an enviroment called "assignment" such that the code

\begin{assignment}
Some words here.
\end{assignment}

will result in "Some words here." in the text and, say, "3 words" in a margin paragraph.

I tried searching for that, but found only (external) tools to count words in the entire document, while I need to do this with LaTeX code and for a single environment (possibly repeated several times in a document).

Dmitry
  • 273

2 Answers2

22

How about counting white spaces? This seems easier to implement.

Here is a simple implement. You can improve it to deal with more complex texts.

\documentclass{article}
\begingroup
\lccode`\~=`\ %
\lowercase{%
  \gdef\assignment{\setcounter{word}{0}%
    \catcode`~=\active
    \def~{\space\stepcounter{word}}}}%
\endgroup
\newcounter{word}
\def\endassignment{\stepcounter{word}%
  \marginpar{\arabic{word} words}}
\begin{document}

\begin{assignment}
Here are some words.
\end{assignment}

\end{document}
Leo Liu
  • 77,365
12

Here's an environment that counts word inside. It uses the xesearch package, so it requires XeLaTeX.

Searching is kept local to the environment, that's why it's defined inside.

\documentclass{article}
\usepackage{xesearch}
\newcounter{words}
\newenvironment{assignment}{%
  \setcounter{words}{0}
  \SearchList!{wordcount}{\stepcounter{words}}
    {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?}
  \UndoBoundary{'}
  \SearchOrder{p;}}{%
  \StopSearching
  \marginpar{\arabic{words} words}}
\begin{document}
\begin{assignment}
Here are a few words for a word count demonstration.
\end{assignment}
\end{document}

word count example

Stefan Kottwitz
  • 231,401
  • I have been using this environment without problem until suddenly getting a Tex capacity exceeded, sorry [save size=50000]. I think it might be related to the fact that every page is generating an Underfull \vbox (badness 10000) has occurred while \output is active error. – DGarside Feb 22 '13 at 10:36
  • 1
    This environment doesn't seem to work with the version of XeLaTeX packaged in TeXLive 2016. Can anyone update it for the recent changes? – rpspringuel Feb 07 '17 at 03:48
  • http://tex.stackexchange.com/questions/324151/wordcount-with-xesearch-errors contains the relevant fix for current XeLaTeX. – Joe Corneli Mar 22 '17 at 22:56