Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 如何在Python 2.7中使用星号替换文本文件中的几个不同字符?_Python 2.7_File_Text_Replace_Asterisk - Fatal编程技术网

Python 2.7 如何在Python 2.7中使用星号替换文本文件中的几个不同字符?

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

我试图从文本文件中删除那些字符“{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()
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))