开发者

Python - go to two lines above match

In a text file like this:

First Name last name #

secone name

Address Line 1

Address Line 2

Work Phone:

Home Phone:

Status:

First Name last name #

....same as above...

I need to match st开发者_C百科ring 'Work Phone:' then go two lines up and insert character '|' in the begining of line. so pseudo code would be:

if "Work Phone:" in line: go up two lines: write | + line write rest of the lines.

File is about 10 mb and there are about 1000 paragraphs like this. Then i need to write it to another file. So desired result would be:

First Name last name #

secone name

|Address Line 1

Address Line 2

Work Phone:

Home Phone:

Status:

thanks for any help.


This solution doesn't read whole file into memory

p=""
q=""
for line in open("file"):
    line=line.rstrip()
    if "Work Phone" in line:
       p="|"+p
    if p: print p
    p,q=q,line
print p
print q

output

$ python test.py
First Name last name #
secone name
|Address Line 1
Address Line 2
Work Phone:
Home Phone:
Status:


You can use this regex

(.*\n){2}(Work Phone:)

and replace the matches with

|\1\2

You don't even need Python, you can do such a thing in any modern text editor, like Vim.


Something like this?

lines = text.splitlines()
for i, line in enumerate(lines):
    if 'Work Phone:' in line:
        lines[i-2] = '|' + lines[i-2]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜