2022-07-09, 18:47
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)) |
import re
s = 'a b c'
print(re.sub('\s+',' ',s))
2014-12-14, 18:53
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) |
#!/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)