[Tutor] Removing open bracket, content, close bracket content...

Alan Gauld alan.gauld at btinternet.com
Wed Jan 13 18:29:38 EST 2016


On 13/01/16 22:25, Sam Starfas via Tutor wrote:

Hi Sam,

Could you repost using plain text please?
As you can see below the htnml/rich text option destroys the formatting
of the data and code making it near impossible to read.

> Hi,I am new to Python and trying to create a script that will remove content wrapped in brackets.For example I want to remove from each line the following:[!L] [20][!20+:2]etc....
> But when I run my script I only get the last line of the content. It is correct as far as the output I want, but I don't understand why the other lines disappear. 
> Here is my data:
> [!L]KEXITSETUP=Exit Setup[20]KEXITPSSETUP=Exit PS Setup[20]KEXITCOLSETUP=Exit Color SetupKSERVERSETUP=Server Setup[!L]KPRINTERSETUP=Printer Setup[!L]KNETWORKSETUP=Network Setup[!L]KJOBLOGSETUP=Job Log Setup[!L]KLANGUAGESETUP=Language Setup[!L]KCHANGEPASSWRD=Change Password[!L]KCLRSRVR=Clear Server[!L]KFACTORYDFLT=Factory DefaultsSETUPB1=Setup[20+:2]KPSERROR=Print to            PS Error[20+:2]PSERROR=Print to            PS Error[20+:2]EFPSError=Print to            PS Error
> 
> ----------------------------------------------------------------Here is the script I have so far (remember I am new):
> import re
> with open("lcd_eng.dct") as f:    with open("out.txt", "w") as f1:        for line in f:            if f == 0 or not line.lstrip().startswith('#'):                f1.write(line)
> # Converts the = sign to a , comma for generation of the .csv filef = open("out.txt",'r')filedata = f.read()f.close()newdata = filedata.replace("=",",")f = open("out2.txt",'w')f.write(newdata)f.close()
> # Should strip out anything [...] f1 = open("out2.txt",'r')newdata = f1.read()f1.close()newdata = re.sub(r'\[[^>]*\]', '', newdata)f1 = open("end.txt",'w')f1.write(newdata)f1.close()
> 

As a guess, the problems you are facing is probably that you are
throwing away (or overwriting) the results inside a loop somewhere
and only the last line gets kept. You probably need to create a list and
append each result to the list.

But without being able to read your code that's only a guess.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list