Posts tagged ‘RegExp’

Mit Python mehrfache Leerzeichen durch ein einziges ersetzen

Der folgende Trick hat mir einige Klimmzüge erspart. In einer Textdatei gab es an diversen Stellen mehrfache Leerzeichen, die ich durch ein einzelnes ersetzen wollte.

Ich hätte jetzt einfach so lange doppelte Leerzeichen durch ein einzelnes ersetzen können, bis keine doppelten Leerzeichen mehr vorhanden sind, über einen regular expression geht es aber viel eleganter.

import re
 
s = 'a     b     c'
 
print(re.sub('\s+',' ',s))

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Checking TeX files for cite-errors

Today I had to TeX a longer file with numerous \cite[somestuff]{citekey} sequences, of which some had hard-to-spot errors (some ‚]‘ were missing). The following Python script checks if each \cite command has matching '[]' and '{}' sequences. I’ll probably extend this script to accept simple \cite{citekey} sequences that have no optional parameter.

#!/usr/bin/python
import re
 
with open('filetocheck.tex') as f:
	content = f.readlines()
 
index = 0
 
for a in content:
	index = index + 1
	if "cite"  in a: # check only lines that contain 'cite'
		matches = re.search(r'(.*)\[(.*)\]\{(.*)\}',a) # search for <sometext>[<sometext>]{<sometext>}
		if not matches:
			print (">>> Fail in row" , str(index), a)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website