Environment that counts words inside

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).

-
My "obligatory latex3 answer"-sense is tingling. –  Seamus Feb 1 '11 at 16:00
This is a soluion for ConTeXt, maybe it can be adapted to LaTeX, as well: Dynamically count and return number of words in a section –  Marco Apr 11 '12 at 16:57

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}

-
Thank you, it would suffice. –  Dmitry Feb 1 '11 at 16:33

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}


-
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