summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--python/003-parsing-ascii-table/run.py45
-rw-r--r--python/003-parsing-ascii-table/test-output.txt7
2 files changed, 52 insertions, 0 deletions
diff --git a/python/003-parsing-ascii-table/run.py b/python/003-parsing-ascii-table/run.py
new file mode 100644
index 0000000..96f247c
--- /dev/null
+++ b/python/003-parsing-ascii-table/run.py
@@ -0,0 +1,45 @@
+#!/usr/bin/python
+# part of https://fedorapeople.org/cgit/jpokorny/public_git/snippets.git
+# (c) Jan Pokorny, license determined per COPYING file in the repository's root
+
+from __future__ import print_function
+
+from pprint import pprint
+from sys import argv, stdin
+from re import compile as re_compile, M as re_M
+#from timeit import timeit
+
+
+def run(s, c=2):
+ ret = (l.split('|')[c].strip() for l in s.splitlines() if l.startswith('|'))
+ next(ret)
+ return ret
+
+def run2(s, c=2):
+ re_col = re_compile("[|](?:[^|]*[|]){%d}\s*([^|\s]*)\s*[|]$" % (c - 1), re_M)
+ return (m.group(1) for m in re_col.finditer(s))
+
+if __name__ == "__main__":
+ f = stdin
+ if len(argv) > 1:
+ try:
+ f = open(argv[1], 'r')
+ except StandardError:
+ pass
+ s = f.read()
+ if f is not stdin:
+ try:
+ f.close()
+ except IOError:
+ pass
+ pprint(run(s))
+ #print(timeit(lambda: run(s)))
+ pprint(run2(s))
+ #print(timeit(lambda: run2(s)))
+
+# i7-3520M@2.9 | Python2.7.5 Python3.3.2
+# -------------+------------------------
+# run + tuple | 6.228024 8.395348
+# run + gen. | 3.118867 3.713577
+# run2 + tuple | 11.808680 14.093615
+# run2 + gen. | 3.926764 3.470380
diff --git a/python/003-parsing-ascii-table/test-output.txt b/python/003-parsing-ascii-table/test-output.txt
new file mode 100644
index 0000000..44666cb
--- /dev/null
+++ b/python/003-parsing-ascii-table/test-output.txt
@@ -0,0 +1,7 @@
++----+----------------------------+
+| ID | Hypervisor hostname |
++----+----------------------------+
+| 1 | frk-02.mpc.lab.example.com |
+| 3 | frk-04.mpc.lab.example.com |
+| 6 | frk-03.mpc.lab.example.com |
++----+----------------------------+