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

时间:2014-01-24 17:58:46

标签: python regex

我正在尝试从文本文件中删除花括号。这是我的代码

这是我的文本文件

(        .    ||         .              )   


      .      =               


                         (){



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

                ()

它不能正常工作

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

有什么建议吗?

我得到了解决方案,没有使用重新

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

5 个答案:

答案 0 :(得分:3)

您的模式{{.*?}}会将foo{{bar}}baz之类的字符串更改为foo baz。但是由于你的文件中没有{{bar}}这样的内容,我认为这不是你想要做的。

如果您要删除{}个字符,请尝试以下操作:

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

另请注意,symbols.sub(" ",result)会将其替换为空格。如果您只想删除它们,请使用symbols.sub("",result)

当然,对于这种简单的,正则表达式的东西可能有点过分。基本字符串操作函数可能就足够了。

答案 1 :(得分:3)

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

应该可以正常工作,我喜欢

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

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

如果你做了很多更换,它可能会更快。

答案 2 :(得分:2)

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)

答案 3 :(得分:0)

RE 这很慢,我建议使用简单的replace

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

答案 4 :(得分:-1)

以下内容将从mystring中删除所有卷曲。

import re

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