0

I have one old shell script which include sed command as below. The source data($Tmp) is a HTML table.

sed '/<table border/,/table>/d' $Tmp > $Out

Can someone help me to convert this command to Python script? I really can't figure out how to do that with regular expression. Many thanks..

3 Answers 3

1

Here's a simple implementation.

Briefly, it opens the file, iterates line by line and prints each line to the output. If it matches "<table border", delete flag set to True and following lines aren't printed to the output until it matches "table>".

import sys

f = open(sys.argv[1])
delete = False
for line in f:
    if delete == False:
        if "<table border" in line:
            delete = True

    if delete == False:
        print line,

    if delete == True:
        if "table>" in line:
            delete = False        
Sign up to request clarification or add additional context in comments.

1 Comment

using re to search for a plain string within an other string is a bit overkill, a simple in would be enough.
0

The script copys all lines from the input file to the output file, unless it finds a line containing <table border, then it deletes all lines until it finds /table> and continues writing all further lines.

So one possibility would be:

with open('in') as inf, open('out', 'w') as outf:
    while True:
        line = inf.readline()
        if '<table border' in line:
            while True:
                line = inf.readline()
                if not line or '/table>' in line:
                    line = inf.readline()
                    break
        if not line:
            break
        outf.write(line)

Comments

0
import sys
with open(sys.argv[1]) as f:
    for line in f:
        if '<table border' in line:
            for line in f:
                if 'table>' in line:
                    break
        else:
            sys.stdout.write(line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.