PythonWrite a script parsing file
---- based on Red Hat Enterprise Linux Server release 6.4 (Santiago) ; python 2.6.6
Requirements: 1. Remove empty lines
2. Remove empty lines and output to a new file
Additional requirements (typesetting): 1.'-' indent n characters
'-' indent 2n characters
etc.
2.'-' all sentences beginning with output in one line
'-' the beginning of the sentence output in one line
etc.
-------------------------------------------- Divider Line ------------------------------------------------------
Getting to the point, I didn't touch Python How to manipulate strings, but it's easier to feel.
Idea:1. To parse a file, first open the file
2. to output a new file, write a file locally and write the parsed file in
3. remove the empty line to identify the empty line first, using split (), if spli () cannot return a value, the description is empty line
4. on the problem of typesetting indentation, first to identify the different types of sentences, with the regular match, and then output the string when the front with a space, so it is indented.
Code:
#!/usr/bin/python
#coding =utf-8
Import re
# # # will use a regular match, so enter the re module
old_file=open (' path + filename ', ' R ')
# # # Open a file to parse
download_file=open ('/root/desktop/lianxi/newfile ', ' W ')
# # # Local Create a new file, write the parsed content
Lines=old_file.readlines ()
###.readlines () reads the entire file, parses it into a list of rows
For L in lines:
Match=re.match (R ' ^\-\w.* ', L)
# # # matches the first character is -the sentence
if match:
A=match.group ()
# # # to assign a match result to a
download_file.write ("+a")
# # # Add two spaces to the front of a and write download_file
Match1=re.match (R ' ^\-\-\w.* ', L)
if Match1:
B=match1.group ()
download_file.write ("+b")
if L.split ():
Download_file.write (L)
# # # used to split split, separated by space, empty line natural 0
print "Success"
old_file.close ()
Download_file.close ()
Sina Weibo
@ Leather likes to play basketball
Python writes a script parsing file