第一个python程序

  版本上线,有个洗数据的流程。

  根据一个文件,把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('
')
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 += ");
"
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的用法 简单应用了下

原文地址:https://www.cnblogs.com/firstForEver/p/7679269.html