Skip to content

Instantly share code, notes, and snippets.

@gdetor
Created February 7, 2023 00:05
Show Gist options
  • Save gdetor/fa10475ce1162c753542df16233e67d4 to your computer and use it in GitHub Desktop.
Save gdetor/fa10475ce1162c753542df16233e67d4 to your computer and use it in GitHub Desktop.
Words counting for LaTeX files (Python, bash)
#!/usr/bin/python
# A minimal script that counts the number of words in a LaTeX file.
# Example of use:
# localhost@name$ wclatex filename
import re
import sys
def word_counter(filename):
try:
fp = open(filename, 'r')
except IOError:
print 'File does not exist!'
else:
lines = fp.readlines()
latex_pattern = re.compile('^[\\\\]|^[$]|[=]|[-]|[+]|\w\(')
w_space_pattern = re.compile('\s')
sp, word, latex_word = 0, 0, 0
for i in lines:
buf = i.split(" ")
for j in range(len(buf)):
if latex_pattern.match(buf[j]):
latex_word += 1
elif w_space_pattern.match(buf[j]):
sp += 1
else:
word += 1
return word
if __name__ == '__main__':
if len(sys.argv) == 2:
print word_counter(sys.argv[1])
else:
print 'Use >> python wclatex filename'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment