tags:

views:

70

answers:

4

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 string '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.

A: 

Something like this?

lines = text.splitlines()
for i, line in enumerate(lines):
    if 'Work Phone:' in line:
        lines[i-2] = '|' + lines[i-2]
eumiro
No, it doesn't work: SyntaxError: keyword can't be an expression
mtpython
It works for me. Have you copied it exactly, because it sounds as if one of the variable names has been replaced by a python keyword.
neil
@mtpython - you may want to create the lines list from the text variable first...
eumiro
A: 

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.

Chetan
sorry i dont have vim. i did lots of edits with this file with python so i just want to use python.
mtpython
[Python's regular expression module](http://docs.python.org/library/re.html)
intuited
A: 

Have your program remember the previous two lines:

prev1, prev2 = None, None
for cur in file:
    if 'Work Phone:' in cur:
        print '|',
    print prev2,
    prev2 = prev1
    prev1 = cur
print prev2,
print prev1,
larsmans
+1  A: 

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:
ghostdog74
this works, thank, but how i can write it to file?
mtpython
to write to file:-> `python myscript.py > t`. Or you can do `open()` in the script. `o=open("out.txt","w"); ... o.write(...+"\n"); ...o.close()`
ghostdog74
i forgot about > t. but it removes all blank lines from the file. it works nevertheless.
mtpython
ok, then change `if p: print p` to just `print p`
ghostdog74