[英]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.