Python interview-text to JSON & zip & with statement

Source: Internet
Author: User
Tags text to json

A small example of your own writing is to convert the local TXT file to JSON format output.


Data source

Simple 1-10 Save a file, A-j save a file


Import Jsonbook = ' C:\Python27\\book.txt ' date = ' C:\Python27\date.txt ' book_list = []date_list = []with open (book) as B:
   book_list = B.read (). Splitlines () with open (date) as D:    date_list = D.read (). Splitlines () data = Dict (Zip (book_list , date_list)) print type (data) print Dataj = json.dumps (data) print type (j) Print J

It's easy to read the file from the local and then open the file with the WITH keyword with the Open method. Ignore ' \ n ' When reading the file, otherwise a pair ' \ n ' will appear in the final result: ' \ n '.

With open (fname) as f:    content = F.readlines ()
will get ' \ n '

With open (fname) as f:    content = F.read (). Splitlines ()
Won't get ' \ n '

Then we combine the two list with a Zip method, convert it to the Dict dictionary type, and then convert it to JSON format output using the Json.dumps method.


<type ' dict ' >{' A ': ' 1 ', ' C ': ' 3 ', ' B ': ' 2 ', ' E ': ' 5 ', ' D ': ' 4 ', ' G ': ' 7 ', ' F ': ' 6 ', ' I ': ' 9 ', ' H ': ' 8 ', ' J ': ' Ten '}&L T;type ' str ' >{"A": "1", "C": "3", "B": "2", "E": "5", "D": "4", "G": "7", "F": "6", "I": "9", "H": "8", "J": "10"}


############################################################################################################### #####################


Zip ()

First we look at Help (Zip)


Zip (...)    Zip (seq1 [, SEQ2 [...]]), [(Seq1[0], seq2[0] ...), (...)        Return a list of tuples, where each tuple contains the i-th element from each of the    argument sequences.  The returned list is truncated in length to the length of the    shortest argument sequence.

The zip accepts a series of iterated objects as parameters, the corresponding elements in the object are packaged into a tuple, and the list of these tuples is returned. P.S. If the parameters passed in are unequal, the returned list is the same length as the shortest object in the parameter.


Z1=[1,2,3]z2=[4,5,6]result = Zip (z1,z2) Print Resultz3=[4,5,6,7]result = Zip (z1,z3) Print Resultresult = Zip (*result) Print result# result[(1, 4), (2, 5), (3, 6) [(1, 4), (2, 5), (3, 6) [(1, 2, 3), (4, 5, 6)]

With the asterisk operator, we can unzip the zip list and restore the original two list to a tuple.


Advanced Application Examples

Row and column transformation of two-dimensional matrix

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]

print [[Row[col] for row under a] for Col in range (len (a[0))]# result[[1, 4, 7], [2, 5, 8], [3, 6, 9]

or use zip to map to achieve the same effect

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print zip (*a) print map (List,zip (*a)) # result[(1, 4, 7), (2, 5, 8), (3, 6, 9)][[1, 4, 7], [2, 5, 8], [3, 6, 9]

Using the zip inversion dictionary

m = {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}print m.items () Print zip (M.values (), M.keys ()) mi = dict (Zip (m.values (), M.keys ())) Prin T mprint mi# result[(' A ', 1), (' C ', 3), (' B ', 2), (' d ', ' 4 ') [(1, ' a '), (3, ' C '), (2, ' B '),]{' a ': 4, ' C ': 1, ' B ': 3 , ' d ': 4}{1: ' A ', 2: ' B ', 3: ' C ', 4: ' d '}


With statement

The essence of with is a control flow statement that can be used to simplify the try-finally statement. The main function is to implement a class __enter__ () and a __exit__ () method

Class Controlled_execution:    def _enter__ (self):        set things        to return thing    def __exit__ (self, type, Value,  traceback):        tear Thing Downwith controlled_execution () as thing:    some code

In the actual running process, first run the code inside enter, return thing, as the value of the variable after as, and then run the code in the With module, and then automatically execute the code in exit, regardless of the code in with the result of the run.

This simplifies the try-finally statement as well. Also used in the operation to read the file, the file closed operation in the Exit method, you will not forget to release the file and an error occurred.

The return value of the P.S. Exit method can be used to indicate whether the exception that occurs with the code of the with section needs to be raise, and if False is returned, it is raise, otherwise, no action is made.


In addition, the Contextlib module in the Python library allows you to use a class with the __enter__ and __exit__ methods without having to construct a

>>> from contextlib import ContextManager  >>> from __future__ import with_statement  >> > @contextmanager ...  def context (): ...     print ' Entering the zone ' ...     Try: ...         Yield  ...     Except Exception, E:  ...         print ' with ' error%s '%e ...         Raise e  ...     else: ...         print ' with no error '  ...  >>> with Context ():  ...     print '----in context call------'  ...  Entering the Zone  ----in context------with  no error  

From contextlib import closing  import urllib with    closing (urllib.urlopen (' http://www.python.org ')) as page: For line in      page:          Print Line  


P.s. After a with, you can open multiple files, such as

def filter (TXT, oldfile, newfile):    "Read a list of names from a file line to line to an    output file.    If a line begins with a particular name, insert a string of text after the name before appending the line to the    OUTPU T file.    "    With open (NewFile, ' W ') as outfile, open (Oldfile, ' R ', encoding= ' Utf-8 ') as infile: For line in        infile:            if Line.st  Artswith (TXT): line                = Line[0:len (TXT)] + '-truly a great person!\n '            outfile.write (line) # Input the name of you want To check Againsttext = input (' Please enter the name of a great person: ')    Letsgo = filter (text, ' Spanish ', ' Spanish2 ' )




Reference:

Http://www.cnblogs.com/diyunpeng/archive/2011/09/15/2177028.html

http://blog.csdn.net/largetalk/article/details/6910277

Http://www.cnblogs.com/Brogrammer/archive/2012/07/23/2605570.html

Http://effbot.org/zone/python-with-statement.htm

Python interview-text to JSON & zip & with statement

Related Article

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.