The first Python program

Source: Internet
Author: User

Version on-line, there is a process of data washing.

Generate SQL based on a file.

Accustomed to the use of PHP, a very simple few lines of code to write it out. Because I did not write Python, I would like to use the py write down, although there is no technical content, it will be practiced.

The original file format is as follows:

 30001  ,bacdh45101  30001  ,bachxz5101  30002  ,bacjd45101  30003  ,bactg45101  30003  ,baglp45101  30004  ,bayxj45101  30004  ,bfakj41101  30005  ,bfbdz41102  30005  ,bfbdz41119 .........

PHP Code:

$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/python2 3File_object = open ('Flushdata.log')4 Try:5Contents =File_object.readlines ()6D = {}7       forLineinchContents:8SP = Line.split (',')9TAGC =Sp[0]TenMID = Sp[1].strip ('\ n') One         ifTagcinchD: A D[tagc].append (mid) -         Else : -D[TAGC] =[mid] the  -arr =Sorted (D.keys ()) -  -str ="" +       forTagcincharr: -str + ="Update list Set tag="+ TAGC +"where mid in (" +str + ="'"+"', '". Join (D[TAGC]) +"'" Astr + ="); \ n" at  -File_object = open ('Flushdata_py.sql','W') - file_object.write (str) - file_object.close () -  - finally: inFile_object.close ()

After execution, diff the two files in the same

diff -b-b  flushdata_php.sql flushdata_py.sql

Python syntax is not familiar, the first time to write more blunt ...

The use of a variety of colon tab,dict and lists is simply applied

The first Python program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.