[英]How to remove curly braces from text file?
我正在尝试从文本文件中删除花括号。 这是我的代码
这是我的文字档
( . || . )
. =
(){
= . ? . (" ") : . .
. . = ( )+8+" "
( && _ (" ")!="")
()
它不起作用
import re
symbols =re.compile(r'{{.*?}}',flags=re.UNICODE)
result = symbols.sub(" ",result)
有什么建议么?
我得到了解决方案,而无需使用re
text.replace('{', '')
text.replace('}', '')
您的模式{{.*?}}
会将foo{{bar}}baz
类的字符串更改为foo baz
。 但是由于文件中没有出现{{bar}}
,因此我认为这并不是您真正想要的。
如果要删除{
和}
字符,请尝试以下操作:
symbols = re.compile(r'[{}]',flags=re.UNICODE)
另请注意, symbols.sub(" ",result)
会将它们替换为空格。 如果只想删除它们,请使用symbols.sub("",result)
。
当然,对于这种简单的正则表达式来说,可能会过分杀伤力。 基本的字符串操作功能可能就足够了。
text.replace('{', '')
text.replace('}', '')
应该工作正常,我喜欢
text = 'abc{def}ghi'
text.translate(None, '{}')
要么
unitext = u'abc{def}ghi'
unitext.translate({ord('{'):None, ord('}'):None})
如果您进行大量更换,它可能甚至更快。
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)
类似于以下内容将删除mystring中的所有卷发。
import re
mystring = 'my stuff with {curly} braces'
result = re.sub(r'[{}]', '', mystring)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.