简体   繁体   English

如何从文本文件中删除花括号?

[英]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 我得到了解决方案,而无需使用re

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

Your pattern, {{.*?}} , will change a string like foo{{bar}}baz to foo baz . 您的模式{{.*?}}会将foo{{bar}}baz类的字符串更改为foo baz But since nothing like {{bar}} appears in your file, I don't think that's really what you want to do. 但是由于文件中没有出现{{bar}} ,因此我认为这并不是您真正想要的。

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. 另请注意, symbols.sub(" ",result)会将它们替换为空格。 If you want to just remove them, use symbols.sub("",result) . 如果只想删除它们,请使用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 : RE这很慢,我建议使用简单的replace

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

Something like the following would remove all curlys from mystring. 类似于以下内容将删除mystring中的所有卷发。

import re

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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