版本上線,有個洗數據的流程。php
根據一個文件,把sql生成出來。python
習慣了利用php,很是簡單的幾句代碼就寫出來。由於沒寫過python,就想用py寫下,雖然沒啥技術含量,也就當練習下。sql
原文件格式以下: app
30001,BACDH45101 30001,BACHXZ5101 30002,BACJD45101 30003,BACTG45101 30003,BAGLP45101 30004,BAYXJ45101 30004,BFAKJ41101 30005,BFBDZ41102 30005,BFBDZ41119 ... ... ...
php 代碼:spa
$data = file_get_contents("flushdata.log"); $arr = explode(PHP_EOL, $data); foreach ($arr as $item){ $items = explode(',', $item); if($tagc = $items[0]){ $temp[$tagc][] = $items[1]; } } $str = ''; foreach ($temp as $key => $val){ $ins = "'".implode("','", $val)."'"; $str .= "update list set tag=". $key. " where mid in (". $ins. ");".PHP_EOL; } file_put_contents("flushdata_php.sql", $str);
py代碼:code
1 #! /usr/bin/python 2 3 file_object = open('flushdata.log') 4 try: 5 contents = file_object.readlines() 6 d = {} 7 for line in contents: 8 sp = line.split(',') 9 tagc = sp[0] 10 mid = sp[1].strip('\n') 11 if tagc in d: 12 d[tagc].append(mid) 13 else : 14 d[tagc] = [mid] 15 16 arr = sorted(d.keys()) 17 18 str = "" 19 for tagc in arr: 20 str += "update list set tag=" + tagc + " where mid in (" 21 str += "'" + "','".join(d[tagc]) + "'" 22 str += ");\n" 23 24 file_object = open('flushdata_py.sql', 'w') 25 file_object.write(str) 26 file_object.close() 27 28 finally: 29 file_object.close()
執行後,diff下倆文件一致blog
diff -b -B flushdata_php.sql flushdata_py.sql
python的語法不太熟悉,第一次寫比較生硬...ip
各類冒號 TAB,dict 和list的用法 簡單應用了下get