版本上線,有個洗資料的流程。
根據一個檔案,把sql生成出來。
習慣了利用php,非常簡單的幾句代碼就寫出來。因為沒寫過python,就想用py寫下,雖然沒啥技術含量,也就當練習下。
原檔案格式如下:
30001,BACDH45101
30001,BACHXZ5101
30002,BACJD45101
30003,BACTG45101
30003,BAGLP45101
30004,BAYXJ45101
30004,BFAKJ41101
30005,BFBDZ41102
30005,BFBDZ41119
...
...
...
php 代碼:
$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代碼:
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下倆檔案一緻
diff -b -B flushdata_php.sql flushdata_py.sql
python的文法不太熟悉,第一次寫比較生硬...
各種冒号 TAB,dict 和list的用法 簡單應用了下