【问题标题】:How to replace several different characters in text file using Asterisk in Python 2.7?如何在 Python 2.7 中使用 Asterisk 替换文本文件中的几个不同字符?
【发布时间】:2020-01-21 12:21:56
【问题描述】:

我尝试使用以下代码从文本文件中删除那些字符 '{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 ================================
>>> 
>>>

我红色:

但没有找到我的解决方案。

【问题讨论】:

    标签: python-2.7 file text replace asterisk


    【解决方案1】:

    我相信最简单的方法是使用regular expressions

    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))
    

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多