,

Category: python

  • Python – yield a text file

    def yield_file(filepath): with open(filepath, ‘r’) as f for line in f: yield line Usage: for line in yield_file(filepath): do_something(line) # whatever you want 🙂

  • Python – Pythonic Collection

    Dictionaries 1. Unpythonic if b != None: a = b else: a = c 1. Pythonic a = b or c 1. Unpythonic if var is None: print(“var is not set”) 1. Pythonic if not var: print(“var is not set”) 1. Unpythonic print(“——————————“) 1. Pythonic print(“-“*30) Keys 1. Unpythonic mydict.has_key(key) 1. Pythonic key in mydict…

  • Python – sh – call shell commands and process results

    # -*- coding: UTF-8 -*- import os, sys def main(): res = sh(‘ls -l’) print res def sh(self, cmd_arg_str, errout=sys.stderr ): import subprocess r””” Popen a shell -> line or “line1 \n line2 …”, trim last \n “”” # crashes after pyqt QApplication() with mac py 2.5.1, pyqt 4.4.2 # subprocess.py _communicate select.error: (4, ‘Interrupted…

  • Postgres – Hamming distance in plpython

    CREATE OR REPLACE FUNCTION util.hamming_distance (s1 text, s2 text) RETURNS integer /* select * from util.hamming_distance (‘hella3’, ‘hillo2’) */ AS $$ return sum([ch1 != ch2 for ch1, ch2 in zip(s1, s2)]) $$ LANGUAGE plpythonu;

  • Python – Hamming Distance

    def hamming_distance(s1, s2): assert len(s1) == len(s2) return sum([ch1 != ch2 for ch1, ch2 in zip(s1, s2)]) def test_hamming_distance(): s1,s2=”0102304″, “9375304” res = hamming_distance(s1, s2) print(res) print((s1,list(zip(s1,s2))))

  • Python – Check List of URLs

    # -*- coding: UTF-8 -*- def main(): source=’/webdev/links-of-urls.txt’; destination=source+”.result” check_urls(source, destination) print(‘done!’) def check_urls(source, destination): with open(source, ‘w’) as fout: with open(source, ‘r’) as fin: for url in fin: pre=”ERR” try: data = urllib2.urlopen(url.trim()).read() pre=”OK” except: print(“Failed…”) fout.write(pre+” “+url) if __name__ == ‘__main__’: main()