Refactoring; arbitrary expression in lists
Nick Craig-Wood
nick at craig-wood.com
Thu Jan 13 03:31:44 EST 2005
Stephen Thorne <stephen.thorne at gmail.com> wrote:
> Why not use a regexp based approach.
Good idea... You could also use sre.Scanner which is supposed to be
fast like this...
import re, sre
scanner = sre.Scanner([
(r"\.php$", "application/x-php"),
(r"\.(cc|cpp)$", "text/x-c++-src"),
(r"\.xsl$", "xsl"),
(r"Makefile", "text/x-makefile"),
(r".", None),
])
def detectMimeType( filename ):
t = scanner.scan(filename)[0]
if len(t) < 1:
return None
# raise NoMimeError
return t[0]
for f in ("index.php", "index.php3", "prog.cc", "prog.cpp", "flodge.xsl", "Makefile", "myMakefile", "potato.123"):
print f, detectMimeType(f)
...
prints
index.php application/x-php
index.php3 None
prog.cc text/x-c++-src
prog.cpp text/x-c++-src
flodge.xsl xsl
Makefile text/x-makefile
myMakefile text/x-makefile
potato.123 None
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list