# Is there any way to do a correct word count of a LaTeX document?

Often assignments (or even papers) have a word count limit. That is not a big deal when using Word, but I don't know how to do that using LaTeX. My solution has been so far to compile the document and then do a rough word count of my pdf file, sometimes even copying the contents of the pdf file and pasting in Word to get a mostly correct Word count.

Is there any tool (maybe even an online tool), package, script or software to do that directly from my .tex document and still get the right word count (i.e., ignore commands, equations, etc)?

• Same question on Stack Exchange: stackoverflow.com/questions/2974954/… – Charles Stewart Jun 18 '11 at 12:07
• Under Linux I normally do it over the PDF to get a rough count: pdftotext file.pdf - | wc -w, but this also counts page numbers etc. as words. – Martin Scharrer Jun 29 '11 at 18:27
• Word count is never perfectly defined: How much words in can't? In an algorithm? In a figure with several texts? So, the notion of correct word count does not exist... – Paul Gaborit Jul 17 '12 at 11:43
• Emacs native tex-mode has a word count function: M-x tex-count-words. – giordano Jun 4 '13 at 8:33
• watches your LaTeX word limit as you type and save: % watch -d "detex index.tex | wc -w" – Vaibhav Bajpai Feb 28 '14 at 19:43

This is in the UK TeX FAQ. The solutions suggested are:

• detex filename (which tries to strip LaTeX commands), then use any word count tool. (e.g. wc)

• latexcount.pl, a Perl script for word count

• texcount, another script even has an online interface

• wordcount, which has a script that runs LaTeX with some settings, then counts word indications in the log file.


my $count = 0; my$first = "";
my $tex = 0; while ($first =~ /^\s*$/) {$first = <>;
}

if ($first =~ /^\$$input|section|setlength|documentstyle|chapter|documentclass|relax|contentsline|indexentry|begin|glossaryentry)/) { tex = sub { r = _[0]; m = _[1]; r =~ s/\\(emph|textbf|textit|texttt|em)\{//g; r =~ s/\\(sub)*section\*?\{[^\}]*\}//; r =~ s/\\title\{[^\}]*\}//; r =~ s/\\\(.*?\\$$/maths/g;$r =~ s/\\$$.*?/maths/; r =~ s/^.*?\\$$/maths/;
$r =~ s/\\$.*?\\$/maths/g;$r =~ s/.*?\\\]// and $m = 0;$m and $r = "";$r =~ s/\\\[.*?$// and$m = 1;
$r =~ s/\\\S*//g;$r =~ s/%.*//;
return ($r,$m) };
} else {
$tex = sub { return ($_[0],0) };
@split = split(" ", $first);$count += $#split + 1; } while ($s = <>) {
($t,$n) = &$tex($s,$n); @split = split(" ",$t);
$count +=$#split + 1;
}

print "Number of words: $count\n";  • @Andrew: again the issue: what do you do with it? how I am supposed to use it? Can you add that to your answer? – Vivi Jul 29 '10 at 8:44 • @Viv: to be honest, I would say that if you don't know what to do with this then you aren't supposed to use it and should use one of the answers in the accepted answer. – Loop Space Jul 29 '10 at 9:18 • I am glad you were born knowing how to do it, otherwise you wouldn't be using it now, right? Because if you don't know it, you are not supposed to learn it, isn't that right? – Vivi Jul 29 '10 at 10:59 • @Vivi: I apologise for the fact that my remark has come across other than I intended it. I did start writing out the instructions, but they are so OS and user specific that I gave up. I'd be happy to help with this sort of thing (though I think that the comments here are not the best format for such help), but in this specific case I really do think that if you don't know how to do it, then this is not the right way to do it. It's an old script that I dug up and it is very me-specific so almost certainly would need a little tweaking to make it useful to anyone. (contd) – Loop Space Jul 29 '10 at 11:09 • @Andrew: In Brazil I am Vivi, but here I am Viv, so you didn't spell it wrong after all! Thanks for your answer. I understand some things are too complicated to explain here, and it is not really the place. This thing (scripts, and pearl) keeps coming up so often that I decided it is time to understand it! I will ask this to someone that lives here and can explain to me in person (about using scripts in general, but I will probably leave yours for later, given what you said). Thanks again for taking the time to explain, and thanks for sharing the code :) – Vivi Jul 29 '10 at 11:58 The first one to come to mind is detex which strips a tex file of commands. You will then have to pass it through wc or some other word counting software. A search on the internet also brought up two items on Sourceforge: word counter 1 and word counter 2. Disclaimer: out of the three, I've only used detex before. It worked reasonably well, but I was working with an English essay and it had no equations, so I don't know how it plays with math mode stuff. (Currently I don't have it installed so I can't check.) • It's been a while since I used it but if I remember correctly, I don't think detex completely strips out the math content of a file, so that might skew the word count. – David Z Jul 29 '10 at 0:47 • I had opportunity to use detex recently and it leaves many TeX-related words which have nothing to do with the content. I would almost go as far as saying that compiling to PDF and then using pdftotext might produce a more accurate count, even when it contains page numbers and repeats the headers. – José Figueroa-O'Farrill Jul 29 '10 at 0:50 • Just tried it on a recent paper I wrote: yeah, detex is wildly off. I get even better results from piping dvi2tty to wc. – Willie Wong Aug 4 '10 at 0:51 • Never used detex, but untex which comes in Debian seems to do the job. – helcim Aug 6 '10 at 15:23 • @José: I found pdftotext to be much better. Especially since I tend to write macros that generate text so stripping them produces wildly incorrect word counts. – TH. Nov 27 '10 at 17:41 I use texcount with the following parameters: texcount file.tex -inc -incbib -sum -1  Output is simple like this: 9079  If you remove the -1, then you can get more information: word count (#headers/#floats/#inlines/#displayed) 3996+48+99 (22/9/0/0) Included file: parts/blup.tex  • great one, best answer – Gery Jul 4 at 20:54 Compile the Tex-File to DVI and then execute  catdvi document.dvi | wc -w  This converts your DVI file to a text-only file and counts the words using 'wc'. • This gets fooled by hyphenation but should be a good approximation. – lhf Jul 17 '12 at 10:46 The last time I had to worry about this, I compiled my LaTeX document to PDF and ran it through pdftotext. • This approach cannot deliver reliable results due to unreliable conversion by pdftotext. – helcim Aug 6 '10 at 15:26 • Do you have an example of how pdftotext fails? I got reasonable results when I used it, but the documents I was using were not particularly elaborate (I don't think they had figures, for example). – Blake Stacey Aug 8 '10 at 18:46 • This will count headers and page numbers in your word count. This will also count lots of words in mathmode. Try doing pdftotext and then wc on a file containing the equation $x+y=z\$. That counts as something like 5 words for this method… – Seamus Jul 17 '12 at 9:55
• @Seamus For documents without much logic or maths, though, I've found it more accurate than alternatives when combined with a script to remove headers, footers etc. For documents with a lot of logic or maths, it would be hopeless. (I have no idea how those should be calculated, either.) – cfr Sep 12 '14 at 23:45

For Windows users, the LaTeX Word Counter is pretty neat.

• The Sourceforge page says it's also available for Linux and Mac. – doncherry Feb 15 '12 at 10:41

In general the answer is NO.

Nearly all requesters of word counts are not interested in the number of words but rather in the amount of space (pages) that the document will need when printed. If there are figures should the words in captions be counted without the space required by the illustration being taken into account? Are equations words, and if so is it one 'word' per variable/symbol or one 'word' per equation? If a paper consists of nothing more than title, author, a sentence and 100 math expressions is that about 50 or 500 'words'? Is a hyphenated word one or two? Does a document that mainly consists of 3 or 4 letter words compare equally with one that has a preponderance of 8 to 10 letter words?

I think that the traditional method is best: print the document, count the average number of 'words' per line in a typical page and multiply by the average number of lines per page and by the number of pages.

It is highly unlikely that the recipient of your work will actually count the number of words.

• :@peterwilson: i don't think that's the case; universities are notorious for setting word counts for dissertations, and then employing a menial to count the words when the copy is submitted. in this case, they don't (really) care about the printed size, they care about the idiot letter of their idiot regulations. (iirc, my university (cambridge) has recently followed down that crazy path, having previously set a page limit.) – wasteofspace Jul 17 '12 at 10:40

If you are on Windows and do not mind purchasing software, use WinEdt. It has a built in word count feature (Document->word count).

In the specific case where Sublime Text is used for writing latex documents, one can use the package LaTeX Word Count.

In addition to Philipp Gesang's answer I'd like to mention how to use the spellchecker module in ConTeXt to count words. It is adapted from the Spellchecker wiki page.

The word count extracted in the wiki includes inline math and content set with \type, though. To have the word count per language without math and \type you have to query categories.document.languages.en.total of the words file array.

\setupspellchecking[state=start,method=2]
\ctxlua{languages.words.threshold=1}

\starttext
\input knuth
\startformula
x_{1,2} = \frac{-b\pm\sqrt{b^2-4ac}}{2a}
\stopformula
\input ward
\m{E = m c^2}

\startluacode
local wordfile = "\jobname.words"
local data = dofile(wordfile)
context.startitemize({"packed"})
context.item("Total words (including inline math): " .. data.total)
context.item("Total words (in language \\type{en}): "
.. data.categories.document.languages.en.total)
context.item("Total unique words (in language \\type{en}): "
.. data.categories.document.languages.en.unique)
context.stopitemize()
end
\stopluacode

\stoptext


• Sorry for the potentially stupid question, but is there any way to use this with lualatex? – bonanza Feb 28 at 18:03
• @bonanza Yes, see Philipp's answer: tex.stackexchange.com/a/54630 It might need some adjustments to run with current LuaTeX though. – Henri Menke Feb 28 at 20:28
• Thanks for your reply. Unfortunately, I am a complete noob regarding (lua)latex. Could I bribe you with some extra reputation to write a complete/noob-safe answer? – bonanza Mar 1 at 8:25

For Mac users, TeXShop (at least version 3.26) has a line, word and character count under Edit>Statistics. I never tested how well it works, but since TeXShop recognises syntax for colour-coding, I assume it is able to ignore most commands for the text.

You can try Microspell. It's a very robust software that knows if you have a main tex document and other subsidiary ones.

If you use the online tool ShareLatex then this now has a built in word count:

https://www.sharelatex.com/blog/2015/09/15/word-count.html

If you are using Overleaf you can click the word count button:

This will show these stats:

You can also easily import an existing document.

Texstudio offers an advanced word count. It is located in the menus under Tools --> Word Analysis.

It refers to words as 'phrases' and offers different options and filters. It can also do word count on specific selection.

I have compared the output to MS Word and LibreOffice Writer, and they are mostly the same. The advantage of Texstudio is that by default it will not count table of contents and bibliography in the total word ('phrase') count. That makes it really convenient to get a reliable estimate on the go as one is editing the document.

Combining texcount + knitr + R allows for dynamic in-text word count estimation. The code chunk below works on a Mac by calling the Texcount Perl script, grabbing the name of the current file (or, running it on myfile.tex) and then returning a limited set of stats (the -total option) including the sum of all words (the -sum) option. As noted elsewhere in this thread, you may want to adjust the texcount options to include things like the bibliography. Once word count is extracted, a comma is added (if appropriate) and can then be referenced inline with the Sweave command \Sexpr{}.

The word count will always be for the second-to-last compile but compiling twice will solve that (much as with bibtex or table/figure references). I believe the code to call Perl from within R varies by platform so you may need to adjust the system() command below for non-Macs.

<<wordcount, echo=FALSE, cache=FALSE>>
# adds comma for printing numbers, from scales package by Hadley Wickham
comma <- function (x, ...) {
format(x, ..., big.mark = ",", scientific = FALSE, trim = TRUE)
}

# To dynamically extract name of the current file, use code below
file_name <- current_input() # get name of file
file_name <- strsplit(file_name,"\\.")[[1]][1] # extract name, drop extension
file_name_tex <- paste0(file_name, ".tex") # add .tex extension

system_call <- paste0("system('texcount -inc -incbib -total -sum ", file_name_tex, "', intern=TRUE)") # paste together texcount system command
texcount_out <- eval(parse(text=system_call)) # run texcount on current last compiled .tex file

# Or, to manually write name of myfile.tex, uncomment and modify line below
# texcount_out <- system("texcount -total -sum myfile.tex", intern=TRUE)

sum_row <- grep("Sum count", texcount_out, value=TRUE) # extract row
pattern <- "(\\d)+" # regex pattern for digits

count <- regmatches(sum_row, regexpr(pattern, sum_row) ) # extract digits
count <- comma(as.numeric(count)) # add comma
@

Word count: \Sexpr{count} % reference R variable in Latex prose


kile the latex editor for the kde (ubuntu) desktop has a word count. It is under the statistics menu

• To have that clear, kile has pretty much nothing to do with ubuntu, or its desktop. – mafp Jan 8 '13 at 0:42
• It is not at all accurate. It is OK to get a rough sense of whether document 1 has more words than document 2 but you could not use it for anything requiring an actual count, even an approximate one. – cfr Sep 12 '14 at 23:39

The prior answers are (I believe) more than adequate for the original question. But for the benefit of others who find this via search, I would like to provide more information.

"Word count" can mean many things. It is not necessarily determined by looking for word boundaries (space and return).

One widely-used measure, at least for U.S. English, is to visualize an old-fashioned typewriter, where each keystroke generates a character (including quote, period, comma, and space). Carriage return is also a character. Then, take the number of characters, and divide by six. This assumes an average word length (in U.S. English) of five letters, plus a space.

The above definition is useful for estimating how many pages will be used in a lengthy, printed book or manuscript. Of course, if you are preparing a PDF with TeX, you know exactly how many pages it uses.

Note that this criterion is not useful for academic papers containing illustrations, tables, and images.

I do not know whether MS Word counts word boundaries, or characters/6. In theory, the result should be almost the same, for lengthy flowing text (U.S. English).

I recently wrote a book, for which the page count measured by characters/6 was 220. The actual page count, using TeX with 5.5"x8.5" layout, was 240 pages including blanks. Not a bad estimate.

You may ask: In the case of a term paper, why not specify number of pages instead of word count? The obvious answer is that the number of pages can be gamed using different fonts, font sizes, or leading.

In bash, try:

detex file.tex | wc -w

The first command detex strips latex commands/comments from the file. The output of that is piped to wc -w, which counts the number of words.

• There are already two other answers focusing on detex. Does your answer add anything new? – Teepeemm Jun 20 '17 at 3:03
• Yes, it adds a bash one-liner for the problem. The others circled around it. – innisfree Jun 20 '17 at 4:22

Here is a quick and simple way to include a word count in a LaTeX document with TeXcount:

2. Make sure Perl is installed and accessible via the perl command (should already be the case on Linux, you can get Perl from here for all OSes)
3. Copy and paste this where you want the word count to appear: Word count: \input{|"perl DOCUMENT_FULL_PATH/texcount.pl -brief -sum -total DOCUMENT_FULL_PATH/mytexfile.tex"}
4. Make sure to run your LaTeX engine with the option --shell-escape (or --tex-option=--shell-escape if you use TeXworks/MiKTeX/texify)