Python 2.7 如何在Python 2.7中使用星号替换文本文件中的几个不同字符?
我试图从文本文件中删除那些字符“{a}”{b}”。。。依此类推,我在文本文件中有250个大括号,使用以下代码:Python 2.7 如何在Python 2.7中使用星号替换文本文件中的几个不同字符?,python-2.7,file,text,replace,asterisk,Python 2.7,File,Text,Replace,Asterisk,我试图从文本文件中删除那些字符“{a}”{b}”。。。依此类推,我在文本文件中有250个大括号,使用以下代码: # -*- coding: cp1255 -*- import sys,codecs,string reload(sys) sys.setdefaultencoding('utf8') root = r"G:\desktop\y\test2.txt" x = open(root) s=x.read().replace('{*}','').replace('-','') x.close
# -*- coding: cp1255 -*-
import sys,codecs,string
reload(sys)
sys.setdefaultencoding('utf8')
root = r"G:\desktop\y\test2.txt"
x = open(root)
s=x.read().replace('{*}','').replace('-','')
x.close()
x=open(root,"w")
x.write(s)
x.close
因为每个花括号中的字母都会变化我在
但在运行此代码后,文本文件中没有任何更改:
>>> ================================ RESTART ================================
>>>
>>>
我是红色的:
但没有找到我的解决方案。我认为,最简单的方法就是使用
import re
data = '''{a} Four score and seven years ago our fathers brought forth on this continent, {b} a new nation, {c} conceived in Liberty, {d} and dedicated to the proposition that all men are created equal.
'''
pattern = re.compile(r'\{[A-Za-z]\}')
print(pattern.sub('{*}', data))