简体   繁体   中英

How to remove curly braces from text file?

I am trying to remove curly braces from text file. This is my code

This is my text file

(        .    ||         .              )   


      .      =               


                         (){



              =        .              ?         .              ("              ") :         .   .                  
                    .     .    =        (           )+8+"  "        
     (                     &&    _      ("               ")!="")    

                ()

it is not working

import re
symbols =re.compile(r'{{.*?}}',flags=re.UNICODE)
result = symbols.sub(" ",result)

Any suggestions?

I got solution, without using re

text.replace('{', '')
text.replace('}', '')

Your pattern, {{.*?}} , will change a string like foo{{bar}}baz to foo baz . But since nothing like {{bar}} appears in your file, I don't think that's really what you want to do.

If you want to remove { and } characters, try this:

symbols = re.compile(r'[{}]',flags=re.UNICODE)

Also note that symbols.sub(" ",result) will replace them with spaces. If you want to just remove them, use symbols.sub("",result) .

And of course, for something this simple, regular expressions are probably overkill. Basic string manipulation functions will probably suffice.

text.replace('{', '')
text.replace('}', '')

should work fine, I like

text = 'abc{def}ghi'
text.translate(None, '{}')

or

unitext = u'abc{def}ghi'
unitext.translate({ord('{'):None, ord('}'):None})

It's probably even faster, if you do a lot of replacing.

with open('output_file', 'w') as f_out:
    with open('input_file') as f_in:
        for line in f_in:
            for ch in ['{', '}']:
                line = line.replace(ch, '')
            f_out.write(line)

RE it is very slow, i suggest to use simple replace :

text.replace('{', '')
text.replace('}', '')

Something like the following would remove all curlys from mystring.

import re

mystring = 'my stuff with {curly} braces'
result = re.sub(r'[{}]', '', mystring)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM