Python core Programming Chapter 9th exercise: 9-7

Source: Internet
Author: User
Tags aliases


parse the file. Win32 User: Creates a program to resolve Windows. ini files. POSIX User: Create a program that resolves/etc/serves files. Other platform users: Write a program that parses a system configuration file for a particular structure.


The online example is mostly parsing Windows Win.ini, which is relatively simple.


This is the parsing/etc/services, because some columns (columns can be considered as configuration items) may be empty, and you need to do some processing on how to remove columns and determine which columns might be empty.


To parse the result with Dict storage:

The name of each key of the dict is the first column of the row (the service name), and the value of this key is a list of other elements of the row, and each element of the list appears as a configuration item name = Configuration Item value.


# coding:utf-8import re#  read the file in,  each row is stored to list,  continuously increasing the list element,  Comment line ignored Def file_ Analyze (fname):     line_list = list ()     with open ( fname,  ' R ')  as fd:        for eachline in  fd:            if eachline.startswith (' # '):                 continue             line_list.append (Eachline)      return line_list#  with a dict store parsing results, each element of the  dict is a list, dict of each key-value pair is the parse result of each line #   How to differentiate each column? The 12th column distinguishes the method with the Space #  fourth column uses the # to divide out the line #  the 34th column distinguishes the method is to remove each row fourth column,  then removes the first column and the second column #  Where the third and fourth columns are likely to be empty, # item is the Def column_analyze (file_list) of each line of the file:    for  Item in file_list:  &nbsP;     line_analyze_list = list ()          service_name, tmp_port_protocol, port_protocol, aliases, comment =              str (),  str (),  str (),  str (),  str ()         if len (Item.strip (' \ n '). Strip (' \s '))  ==  0:            continue         for unit in re.split ('//s+ ',  item):             service_name = unit.split () [0]             tmp_port_protocol = unit.split () [1].strip ()             port_protocol =  ' Port_ protocol =  '  +&nbsP;unit.split () [1].strip ()             line_analyze_ List.append (Port_protocol)             tmp_aliases  = unit.split (' # ') [0].strip (Service_Name). Lstrip () .                 strip (Tmp_port_protocol)              if len (Tmp_aliases.strip ())  == 0:                 aliases =  ' aliases =   '             else:                 aliases =  ' aliases =   '  + unit.split (' # ') [0].                      strip (service_name) .                     lstrip (). Strip (Tmp_port_protocol). Strip ()              line_analyze_list.append (aliases)              if unit.find (' # ')  < 0:                 comment =   ' comment =  '             else:                 comment =   ' comment =  '  + unit.split (' # ') [1].strip (). strip (' \ n ')              line_analyze_list.append (comment)             &nBsp;analyze_dict[service_name] = line_analyze_list    return analyze_ Dictdef main (fname, listname):     listname = file_analyze (fname)      analyze_dict = column_analyze (listname) if __name__ ==  ' __main__ ':     analyze_list = list ()     analyze_dict = dict ()     file_name =  '/etc/services '     main (file_name,  Analyze_list)     print analyze_dict




This article is from the Linux and networking blogs, so be sure to keep this source http://khaozi.blog.51cto.com/952782/1896307

Python core Programming Chapter 9th exercise: 9-7

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.